import csv
phone = input("Enter phone name")
os = input("Enter OS")
with open("phos.csv", "a") as phos:
phos_dict = csv.DictWriter(phos, fieldnames = ["phone_model", "phone_os"])
phos_dict.writerow({"phone_model": phone, "phone_os": os})
上面的代码工作得很好,即使我把CSV文件空着。那么代码怎么知道如何正确地实现/写入字典到phos.csv文件呢?
1条答案
按热度按时间wnavrhmk1#
它之所以有效,是因为您设置了
fieldnames
,然后,当您发送带有正确键的dict时,代码知道将值放在哪里。如果您在
phos_dict.writerow({"phone_model": phone, "phone_os": os})
中传递一个key:value
,而在fieldnames = ["phone_model", "phone_os"]
中没有实现,则会得到以下错误:ValueError: dict contains fields not in fieldnames