lol.txt 如下:
1,2,3\n
\n
4,5,6\n
\n
AwesomeSauce,12.3,10\n
我正在使用的代码:
import csv
NumberAdult = input("Please enter the number of adults: ")
NumberAdult = int(NumberAdult)
NumberChild = input("Please enter the number of children: ")
NumberChild = int(NumberChild)
n = 0
with open ("lol.txt",'rt', newline = '\n') as f:
csv_r = (line for line in csv.reader(f) if line)
for row in csv_r:
entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]
for index, entry in enumerate(entries):
price1 = float(entry[1])
price2 = float(entry[2])
print ("%i. %17s - %5.2f / %5.2f" % (index, entry[0], price1, price2))
choice = int(input("Which package would you like?: "))
packageChoice = (entries[choice])
for row in packageChoice:
name = entry[0]
AdultPrice = float(entry[1])
ChildPrice = float(entry[2])
price = AdultPrice*NumberAdult + ChildPrice*NumberChild
print(name, price)
输出:
请输入成人人数:2
请输入儿童人数:1
0. 4 - 5.00 / 6.00
1. AwesomeSauce - 12.30 / 10.00
您想要哪种套餐?:1
AwesomeSauce 34.6
这意味着它忽略了 lol.txt 的第一行1,2,3\n
- 因为csv.reader()
似乎将此行视为字段名而不是数据。
有没有解决的办法?使用csv.dictreader()
或其他东西来分配独立于文件本身的字段名称?
编辑:没关系csv.reader()
,它不会将它们视为字段名称。所以看起来问题出在这个部分:
with open ("lol.txt",'rt', newline = '\n') as f:
csv_r = (line for line in csv.reader(f) if line)
for row in csv_r:
现在,我不知道该怎么做——这是我让脚本最接近工作的地方。任何提示,搜索词,什么?
最终编辑:没关系,现在一切正常!我有一个我忘记的循环:
for row in csv_r:
entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]
这导致它跳过第一行。感谢 freenode 上#python 的 dash 让我再次看到那条线!
新问题:
import csv
NumberAdult = input("Please enter the number of adults: ")
NumberAdult = int(NumberAdult)
NumberChild = input("Please enter the number of children: ")
NumberChild = int(NumberChild)
n = 0
with open ("lol.txt",'rt', newline = '\n') as f:
csv_r = (line for line in csv.reader(f) if line)
entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]
for index, entry in enumerate(entries):
price1 = float(entry[1])
price2 = float(entry[2])
print ("%i. %17s - %5.2f / %5.2f" % (index, entry[0], price1, price2))
choice = int(input("Which package would you like?: "))
packageChoice = (entries[choice])
for row in packageChoice:
name = entry[0]
AdultPrice = float(entry[1])
ChildPrice = float(entry[2])
price = AdultPrice*NumberAdult + ChildPrice*NumberChild
print(name, price)
唯一的“选项”(无论您输入什么作为选项)是 2.,因为它是通过 list 放入的最后一行entries
。
>>>
Please enter the number of adults: 2
Please enter the number of children: 1
0. 1 - 2.00 / 3.00
1. 4 - 5.00 / 6.00
2. AwesomeSauce - 12.30 / 10.00
Which package would you like?: 1
AwesomeSauce 34.6
>>>
现在,我很确定问题出在此处:
csv_r = (line for line in csv.reader(f) if line)
entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]
for index, entry in enumerate(entries):
或者,我应该为菜单的结果做另一个类似的部分,我不确定。我将努力实现两者以尝试对其进行故障排除。