import csv
students = []
with open("stu1.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']}")
stu1.csv 包含以下数据
Harry, Number, Pivet Drive
Ron, The burrow
Draco, Malfoy manor
你们非常亲密。实际上有2个错误。
append()
需要1个字典,但你传递了2个字典。修复错误后,这可以工作:
import csv
students = []
f = "C:\\test\\test_file.csv"
with open(f) 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']}")
返回这个:
Draco is from Malfoy manor
Harry is from Number
Ron is from The burrow
就上下文而言,我相信这来自 CS50 讲座 (https://www.youtube.com/watch?v=nLRL_NcnK-4&t=28335s&ab_channel=freeCodeCamp.org),时间为 8:00:00 - 8:12: 09.
在他的示例中,David Malan 的输入文件为:
Harry,"Number Four, Privet Drive"
Ron, The burrow
Draco, Malfoy manor
请注意,
,
之后的第一行文本跨越""
内部,这使得csv.reader()
将其识别为单个元素,并且不会引发ValueError: too many values to unpack