Home > Software engineering >  How skip a header in the next loop of writing data in csv file - Python
How skip a header in the next loop of writing data in csv file - Python

Time:11-18

I writting a script, where I dowload a data from json file (about temperature and data from datetime) and I want save the data i csv file. The script has a schedule set every minute to download new data from json. I have a problem with one thing. Running the code causes the data to write correctly, but each time with a header. The question is how to save the header only once?

My script: ...

with open('Temp.csv', 'a', newline='') as file:
    fieldnames = ['Date', 'Temp']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Date':now, 'Temp':Temperatura})

My DataFrame look like this:

enter image description here

but I want: enter image description here

Thanks for help, Dawid

CodePudding user response:

You need to write the header before the first row. So check the existence of the file to decide on writing the header.


import os 

file_exists = os.path.exists('Temp.csv')

with open('Temp.csv', 'a', newline='') as file:
    fieldnames = ['Date', 'Temp']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    if not file_exists:
        writer.writeheader() # So the header is written only once just before the first row
    writer.writerow({'Date':now, 'Temp':Temperatura})

For the rest rows, since the csv file exists, header is not written again.

  • Related