Python 为什么我的csv编写器使用数据作为密钥,我如何修复它?
我正在使用csv库将通过html表单收集的数据写入csv。writer只能在一定程度上工作,因为它将我的数据加倍作为数据的键,使得以后无法访问它。如何修复我的代码 作为一名完全的python初学者,我当然尝试查找我的问题,但没有找到任何合适的解决方案:/Python 为什么我的csv编写器使用数据作为密钥,我如何修复它?,python,flask,Python,Flask,我正在使用csv库将通过html表单收集的数据写入csv。writer只能在一定程度上工作,因为它将我的数据加倍作为数据的键,使得以后无法访问它。如何修复我的代码 作为一名完全的python初学者,我当然尝试查找我的问题,但没有找到任何合适的解决方案:/ # writes the valid data to the csv-file with open("survey.csv", 'a') as file: writer = csv.DictWriter(file, fieldnames
# writes the valid data to the csv-file
with open("survey.csv", 'a') as file:
writer = csv.DictWriter(file, fieldnames=["name", "gender", "preference"])
writer.writerow({"name": request.form.get("name"), "gender": request.form.get("gender"), "preference": request.form.get("pets")})
在使用listreader遍历行时,我希望得到如下输出:
OrderedDict([('name', 'Adrian'), ('gender', 'male'), ('preference', 'dogs')])
相反,我得到的是:
OrderedDict([('Adrian', 'Adrian'), ('male', 'male'), ('dogs', 'dogs')])
这也是我的阅读器代码,也许问题出在这里:
with open("survey.csv","r") as file:
reader = csv.DictReader(file)
participants = list(reader)
for participant in participants:
print(participant)
您的问题是缺少标题,使用csv.Dictwriter写入时,您需要首先使用writer.writeheader写入标题 在您的例子中,似乎您正试图附加到文件中,因此我认为您需要在创建带有标题的文件时进行初始化步骤,然后再按子顺序附加到文件中。否则,每次获取新表单时,都会将标题作为新行获取 比如说
In [2]: data
Out[2]:
[{'name': 'andrew', 'gender': 'm'},
{'name': 'heather', 'gender': 'f'},
{'gender': 'm', 'name': 'john'}]
In [3]: def start_file():
...: with open('out.csv', 'w') as f:
...: w = csv.DictWriter(f, fieldnames=['name', 'gender'])
...: w.writeheader()
...:
In [4]: def write_out(row):
...: with open('out.csv', 'a') as f:
...: w = csv.DictWriter(f, fieldnames=['name', 'gender'])
...: w.writerow(row)
...:
In [5]: start_file()
In [6]: for row in data:
...: write_out(row)
...:
In [7]: with open('out.csv') as f:
...: for row in csv.DictReader(f):
...: print(dict(row))
...:
{'name': 'andrew', 'gender': 'm'}
{'name': 'heather', 'gender': 'f'}
{'name': 'john', 'gender': 'm'}
如果你把要交给writerow的字典打印出来,你会得到什么?书面csv的文本内容是什么?