Python 3:逐步将多个词典写入CSV文件

时间:2018-06-19 09:49:04

标签: python python-3.x csv dictionary

我检查了主题:Writing multiple Python dictionaries to csv file但我认为它还没有回答我的问题。

我有几个词典,如:

{day:1, temperature: 30}
{day:2, temperature: 40}

等等

字典不会立即准备好,而是通过调度程序下载。

我想写一个文件:

day temperature
1 30
2 40

并在新字典进入时继续附加到文件中。

我怎么能用Python 3做到这一点?

非常感谢,

1 个答案:

答案 0 :(得分:3)

使用csv模块和可迭代的字典L

import csv

L = [{'day': 1, 'temperature': 30},
     {'day': 2, 'temperature': 40}]

with open(r'c:\temp\out.csv', 'w', newline='') as f:
    wr = csv.writer(f)
    wr.writerow(['day', 'temperature'])
    for item in L:
        wr.writerow([item['day'], item['temperature']])

结果:

day,temperature
1,30
2,40