我有这个文本文件,分别显示以下信息:
ID, name, rate and value
我已经在这段代码中输入如下所示,但由于某种原因,当我尝试打印名称,速率和值字段时,它给了我一个"列表索引超出范围错误"。ID的范围工作得很好,但其他的没有。我无法使用CSV或任何其他类型的导入工具(由于要求),所以我正在试图找出一种方法来解决这个问题。
def load_customers(self):
file = open('customers.txt', 'r')
i=0
line = file.readline()
while(line!=""):
fields=line.split(', ')
ID=fields[0]
name=fields[1]
rate=float(fields[2])
value=float(fields[3])
self.add_record(ID,name,rate,value)
line=file.readline()
i+=1
file.close()
return (i)
这是因为您的文件中有一个'n'
行,您正在尝试解析。
把它去掉file.readline().strip()
:
def load_customers(self):
file = open('customers.txt', 'r')
i = 0
line = file.readline().strip()
while (line != ""):
fields = line.split(', ')
ID = fields[0]
name = fields[1]
rate = float(fields[2])
value = float(fields[3])
self.add_record(ID, name, rate, value)
line = file.readline().strip()
i += 1
file.close()
return (i)
一种更python化的方法:
def load_customers(self):
i=0
with open('customers.txt', 'r') as f:
for line in f:
line = line.strip()
if line:
fields=line.split(', ')
ID=fields[0]
name=fields[1]
rate=float(fields[2])
value=float(fields[3])
self.add_record(ID,name,rate,value)
i+=1
return (i)