我有一个评估要做,这是我到目前为止的代码:
number1 = input("Number1? ")
number2 = input("Number2? ")
packages = csv.reader(open('lol.txt', newline='\n'), delimiter=',')
for PackName,PriceAdultString,PriceChildString in packages:
n += 1
PriceAdult = float(PriceAdultString)
PriceChild = float(PriceChildString)
print("%i. %17s - $%4.2d / $%4.2d" % (n, PackName, PriceAdult, PriceChild))
NameChoice = input("Which name would you like? Choose using a number: ")
csv.reader 使用的lol.txt 包含以下内容:
herp,123,456
derp,321,654
hurr,213,546
现在,我需要能够使用 NameChoice 从文件中检索一行,并将其中的数据用作 name、number1 和 number2,因此对于 NameChoice == 1、name = herp、number1 = 123 和 number 2 = 456 ,并且数字必须是浮点数。
我很难弄清楚这一点,如果可能的话,可以使用一些指导。
谢谢大家。
在被问到之前,我意识到我忘了提及:我已经用谷歌搜索过,并浏览了 Python 指南和我的教科书。不过,我并不完全相信我知道自己在寻找什么。
遇到一个新问题:我需要能够使用 '\n\n' 而不是 '\n' 来获取 CSV 文本,因此文本更像以下内容:
herp,123,456
derp,321,654
hurr,213,546
我的 Li-Aung 使用的代码(非常轻微调整)版本:
import csv
with open ("lol.txt",'rt', newline = '\n\n') as f:
csv_r = csv.reader (f)
entries = [ (name, float(p1), float(p2)) for name, p1, p2 in csv_r]
for index, entry in enumerate(entries):
print ("%2i. %-10s %5.2f %5.2f" % (index, entry[0], entry[1], entry[2]))
choice = int(input("Choose a number: "))
print (entries[choice])
返回异常:
Traceback (most recent call last):
File "C:/Python32/eh", line 2, in <module>
with open ("lol.txt",'rt', newline = '\n\n') as f:
ValueError: illegal newline value:
现在,调试非常清楚 - '\n\n' 不能作为换行符指定,但我想知道是否有办法解决这个问题?
注意:搞砸了之前的编辑,使用“ newline = '\n'”的代码调试将是:
Traceback (most recent call last):
File "C:/Python32/eh", line 4, in <module>
entries = [ (name, float(p1), float(p2)) for name, p1, p2 in csv_r]
File "C:/Python32/eh", line 4, in <listcomp>
entries = [ (name, float(p1), float(p2)) for name, p1, p2 in csv_r]
ValueError: need more than 0 values to unpack
这是因为它将每个有用行之间具有 0 值的空白区域视为一行,正如它被告知要做的那样,并且那里没有任何内容。