Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I avoid writing CSV header multiple times

I am writing a csv file from a multiple dictionaries with loop.
Where I am using key as a header and dictionaries values as entries.

Saving a csv is perfectly working but header is added each time when new dictionary entries are added to csv.

Is there a way to avoid writing headers multiple times so that I could save csv with a single header and multiple entries from dictionaries.
This is how I am directly saving csv fom multiple dictionaries:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open('./raw_data.csv', 'a', newline='') as f_output:
writer = csv.DictWriter(f_output, fieldnames=header)
writer.writeheader()
  for elem in trainingLogs:
      writer.writerow(elem) 

Where trainLogs is a list which includes nested dictionaries.

Hoping for some help.

THank you

>Solution :

Are you looking for:

csv_file = 'raw_data.csv'
if not os.path.exists(csv_file ):
    f_output = open(csv_file ,'w')
    writer = csv.DictWriter(f_output, fieldnames=header)
    writer.writeheader()
else:
    f_output = open(csv_file ,'a')
    writer = csv.DictWriter(f_output, fieldnames=header)

for elem in trainingLogs:
     writer.writerow(elem)
f_output.close()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading