1

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
gtownrower
  • 135
  • 11

1 Answers1

4

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)
gtownrower
  • 135
  • 11