Search code examples
pythoncsvdictionaryexport-to-csv

How to write dictionary data to csv file?


I have a dictionary like this. I want to write the data inside to csv file but I will run my code over and over again. How can I make it write headers only once? How can I remove the spaces between the lines?

My code

import csv

dl = {7: {'id': 11, 'name': 'Abc', 'age': 35},
      25: {'id': 28, 'name': 'refd', 'age': 88},
      15: {'id': 45, 'name': 'dfgd', 'age': 20}}
id_list = [7, 25, 15]

def to_csv(data):
    fieldnames = ['id', 'name', 'age']
    with open('data.csv', 'a+') as f:
        dict_writer = csv.DictWriter(f, fieldnames = fieldnames)
        dict_writer.writeheader()
        dict_writer.writerow(data)

for i in id_list:
    to_csv(dl[i])

for empty lines solution is

with open('data.csv', newline='', 'a+') as f:

first rub output:

first rub output

second run output:

second run output


Solution

  • How about passing a value to your function to indicate whether or not the headers should be written? Something like this:

    def to_csv(data, writeheader):
        fieldnames = ['id', 'name', 'age']
        with open('data.csv', 'a+') as f:
            dict_writer = csv.DictWriter(f, fieldnames = fieldnames)
            if writeheader:
                dict_writer.writeheader()
            dict_writer.writerow(data)
    id_list = [7,25,15]
    for i in id_list:
        to_csv(dl[i], i==id_list[0])