简体   繁体   中英

Python 3: writing several dictionaries to a CSV file incrementally

I checked the topic: Writing multiple Python dictionaries to csv file but I think it does not answer my question yet.

I have several dictionaries like:

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

and so on

The dictionaries are not ready at once but are downloaded through a scheduler.

I want to write to a file as:

day temperature
1 30
2 40

and continue to append to the file when new dictionaries come in.

How could I do that with Python 3?

Thank you very much,

Using the csv module and an iterable of dictionaries 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']])

Result:

day,temperature
1,30
2,40

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM