I have an assessment to do, and here’s my code so far:
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: ")
The lol.txt used by csv.reader consists of the following:
herp,123,456
derp,321,654
hurr,213,546
Now, I need to be able to use NameChoice to retrieve a row from the file, and use the data within as name, number1, and number2, so for NameChoice == 1, name = herp, number1 = 123 and number 2 = 456, and the numbers must be a floating point number.
I’m having trouble figuring this out, and could use some guidance if that’s possible.
Thanks all.
Before it’s asked, I realised I forgot to mention: I have googled, and trawled through the Python guides, and my textbooks. I’m not entirely convinced I know what I’m looking for, though.
Run into a new problem:
I need to be able to take CSV text with ‘\n\n’ instead of ‘\n’, so the text is more like the following:
herp,123,456
derp,321,654
hurr,213,546
My (very slightly adjusted) version of the code Li-Aung used:
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])
Which returns the exception:
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:
Now, the debug is pretty clear – ‘\n\n’ is not acceptable as a newline specifier, but I was wondering if there is a way around this?
Note: Screwed up the previous edit, the debug from the code with ” newline = ‘\n'” would have been:
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
Which is because it treated the blank space with 0 values between each useful row as a row, as it was told to do, and there was nothing in there.
Store the entire file to a list:
Output: