Home > database >  How do I avoid writing CSV header multiple times
How do I avoid writing CSV header multiple times

Time:12-29

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:

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

CodePudding user response:

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()
  • Related