我有這個文本檔案,分別顯示以下資訊:
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)
uj5u.com熱心網友回復:
這是因為您的檔案中有'\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)
uj5u.com熱心網友回復:
更pythonic方式的方法之一:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311475.html
上一篇:Python中的串列和索引
下一篇:如何遍歷類物件內的串列物件
