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:
CodePudding user response:
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])
CodePudding user response:
dict_writer.writeheader() # write the header in your file
dict_writer.writerow(data) # write the data in your file
So instead of looping these two lines, you should only run writeheader
once and run the writerow
function multiple times.
I will let you figure out the actual implementation