这是我的代码:
while True:
print("Type 'done' to finish receipts")
code=input("Enter item code to add:")
items =open("items.txt")
quant=input("Quantity:")
details = items.read()
detailslist = details.split("\n")
for a in detailslist:
fire = a.split("#")
print (fire)
b = fire[0]
c = fire[1]
d = fire[2]
dictd = {}
dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d
print (dictd)
这在items.txt中:
A# Almanac2018# 18.30
B# Almanac2020# 23.80
C# Almanac2021# 16.54
D# Almanac2022# 22.25
我得到这个错误:
Type 'done' to finish receipts
Enter item code to add:A
Quantity:45
['A', ' Almanac2018', ' 18.30']
{'A': ' Almanac2018 Quantity: 45 Price: 18.30'}
['B', ' Almanac2020', ' 23.80']
{'B': ' Almanac2020 Quantity: 45 Price: 23.80'}
['C', ' Almanac2021', ' 16.54']
{'C': ' Almanac2021 Quantity: 45 Price: 16.54'}
['D', ' Almanac2022', ' 22.25']
{'D': ' Almanac2022 Quantity: 45 Price: 22.25'}
['']
Traceback (most recent call last):
File "receipt.py", line 12, in <module>
c = fire[1]
IndexError: list index out of range
我正在尝试做一个程序,使项目的收据,所以如果你可以提供任何代码,这将是有益的。 任何帮助都将不胜感激
给一个人一条鱼,喂他一天。。。教人钓鱼
因此,这不是鱼,而是鱼竿(只要您使用Python v3.7或更高版本):
这意味着您可以在错误发生时看到“火”的确切形状和大小。这将有助于您在这里以及将来不可避免地出现其他问题时的调试工作
代码中的问题是
items.txt
文件中的空字符串。当存在空字符串时,fire
将解析为['']
,这是一个仅包含1项的列表,因此当代码尝试运行c = fire[1]
时会出现错误。您可以添加检查以查看是否为空行:相关问题 更多 >
编程相关推荐