I’m going through Harvards CS50 Python course, in todays lesson we were introduced to the csv library. I think my code and csv text file contain the exact same text as my instructor but I’m getting a ValueError when using csv.reader(), I’m assuming because of the extra comma in the first key value pair. I’m under the impression that this is exactly what the .reader() function is supposed to prevent? My PyCharm is running the most recent version of python available.
My csv file when opened in the text editor reads as follows:
Harry,Number Four, Privet Drive
Ron,The Burrow
Draco,Malfoy Manor
My code is as follows:
import csv
students = []
with open("students.csv") as file:
reader = csv.reader(file)
for name, home in reader:
students.append({"name": name, "home": home})
for student in sorted(students, key=lambda student: student["name"]):
print(f'{student["name"]} is from {student["home"]}')
I’ve obviously tried changing the first “home” value to a string, so I understand it can be fixed that way. I’m more-so confused why my csv.reader(file) isn’t ignoring the second comma, aka its intended purpose.
The entire error message returns:
python csvtest.py
Traceback (most recent call last):
File “/Users/Julie/PycharmProjects/pythonProject/csvtest.py”, line 10, in
for name,home in reader:
^^^^^^^^^
ValueError: too many values to unpack (expected 2)