为什么我的csv编写器将数据用作密钥,我该如何解决?

时间:2019-06-18 21:34:24

标签: python flask

我正在使用csv库将通过html表单收集的数据写入csv。编写器仅在某种程度上起作用,因为它将我的数据作为数据的密钥加倍,使得以后无法访问它。如何修复我的代码?

作为一个完整的python初学者,我当然尝试查找我的问题,但是我没有找到合适的解决方案:/

# 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")})

我期望这样的输出(当使用list(reader)遍历行时:

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)

1 个答案:

答案 0 :(得分:1)

您的问题是您缺少标题,使用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'} 书写标题
在您的情况下,您似乎正在尝试附加到文件,因此我认为您将需要一个初始化步骤来创建带有标头的文件,然后子序列地附加到该文件。 (否则,每次获得新表单时,标题都将以新行的形式出现)

例如

'layout': Layout(**{
        'title': 'Average Rating by Quarter',
        'xaxis1': {'title':'Date','tickformat':'%b-%y'},
        'yaxis1': {'title':'Number of Conversations'},
        'violinmode':'group'
    })