简体   繁体   中英

Python: Repeatedly writing to a csv file from a dictionary with header equal to key

I am using a dictionary to store scraped values from a table. Then I am writing a row to a csv file. I want to write new rows to a csv file which includes the key as the headers.

I want to write the data to a file mydict.csv, like this:

key1, key2, key3,
value_a, value_b, value_c

I wrote:

import csv

def dict_to_csv(scraped_values_dict): 

    my_dict = scraped_values_dict
     with open('mycsvfile.csv', 'wb') as f:
        w = csv.DictWriter(f, my_dict.keys())
        w.writeheader()
        w.writerow(my_dict)

This method overwrites the previous values. I'd like instead to set the header of the csv file as the keys and with each function call, add a new row with the values. I only want to write the header if the file is empty.

key1, key2, key3, 
value_a, value_b, value_c,
value_d, value_e, value_f

This worked for me:

import csv

def dict_to_csv(scraped_values_dict): 
    my_dict = scraped_values_dict
    with open('mycsvfile.csv', 'a') as f:
        w = csv.DictWriter(f, my_dict.keys())
        if f.tell() == 0:
            w.writeheader()
            w.writerow(my_dict)
        else: 
            w.writerow(my_dict)

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