我无法阅读行中长度不同的文件。具体来说,我知道文件长13行,第1行和第13行有2个值,其余的(2-12)有4个。我想从第1行得到一个值,从第13行得到一个值,第2-12行中的每一行取一个值,取决于它们的先前值是否等于“信用”或“借方”。由于行具有不同的长度,因此我得到“索引超出范围”错误。任何帮助将不胜感激。谢谢!
class Checkbook:
"""Checkbook class for list of check transactions"""
def __init__(self, filename):
"""initializer for Checkbook class"""
self.name = filename
self.debitList = []
self.creditList = []
self.startAmt = 0
self.endAmt = 0
self.shouldBeBal = 0
with open(filename) as csvFile:
readCSV = csv.reader(csvFile, delimiter = ',')
#rowCount = sum(1 for row in readCSV) - 1
#print(rowCount)
next(csvFile)
#in range(1, rowCount, 1):
for row in readCSV:
if (row[2] == " debit"):
debitAmt = row[3]
self.debitList.append(debitAmt)
elif (row[2] == " credit"):
creditAmt = row[3]
self.creditList.append(creditAmt)
答案 0 :(得分:1)
好吧,你必须要避开IndexError
for row in readCSV:
if len(row) > 2: # make sure the row is long enough
if (row[2] == " debit"): # now this can't fail
# ...
elif (row[2] == " credit"):
# ...
或处理它:
for row in readCSV:
try:
if (row[2] == " debit"):
# ...
elif (row[2] == " credit"):
# ...
except IndexError:
pass # do nothing