我目前正在测试我的程序,这个程序基本上是用python中的CSV模块读写一个‘stock’文件。但是我得到了这个错误:IndexError: list index out of range
错误来自程序的这一部分:
def GTIN8Test(): # function validates GTIN
digit8 = input("Please enter the GTIN-8 of the product you want to modify in the stock file: ") # input for GTIN
while digit8.isdigit is False or len(digit8) > 8 or len(digit8) < 8: # checks length of GTIN and characters
digit8 = input("Invalid GTIN-8! Please enter a valid GTIN ")
V1 = int(digit8[0])
V2 = int(digit8[1])
V3 = int(digit8[2])
V4 = int(digit8[3]) # validates GTIN
V5 = int(digit8[4])
V6 = int(digit8[5])
V7 = int(digit8[6])
V8 = int(digit8[7])
V1a = V1 * 3
V3a = V3 * 3
V5a = V5 * 3
V7a = V7 * 3
T1 = V1a + V2 + V3a + V4 + V5a + V6 + V7a + V8
T2 = T1 % 10
if T2 != 0:
print("Your GTIN-8 code",digit8,"is not valid!")
GTIN8Test() # calls function so user can enter another GTIN if theirs is invalid
else:
import csv # imports CSV for reading files
s = open("stock.txt") # opens stock file
counter = 0 # sets counter to 0
while counter != 3: # while counter is not = to 3 this loop keeps running
for stock in csv.reader(s): # checks each line in the stock file6
if digit8 == stock[0]:
print("GTIN-8 is valid and is found in the stock file")
StockMod(digit8) # StockMod is called, carring the GTIN as a paramter
else:
counter = counter + 1 # if no matches on a line are found 1 is added to the counter.
print("GTIN valid but not found in stock file!") # message displays when counter = 3.
s.close() # closes stock file
错误似乎是在函数末尾触发的:
^{pr2}$抱歉,如果有任何格式错误!在
提前谢谢。在
编辑:
以下是完整的错误:
Traceback (most recent call last):
File "C:\Users\Mavro\Documents\School Work\GCSE COURSEWORK\Computer Science\Task 3\Task3MOD (1).py", line 84, in <module>
GTIN8Test() # calls GTIN8Test for StockMod
File "C:\Users\Mavro\Documents\School Work\GCSE COURSEWORK\Computer Science\Task 3\Task3MOD (1).py", line 29, in GTIN8Test
if digit8 == stock[0]:
IndexError: list index out of range
“是怎么做到的?”股票.txt“看起来像?也许文件开头有空行?csv.reader会返回空列表。在这种情况下,您可以在这行之前添加s.readline():
如果每行不是空的,也可以检查:
^{2}$相关问题 更多 >
编程相关推荐