Skip to content Skip to sidebar Skip to footer

Csv Header In Python Only On The Top Row?

i have written a python program which makes an api call to a webserver once every minute and then parse the json response and saves parsed values in to the csv files. here is the c

Solution 1:

You could wrap the writerow function to have it automatically add the header if needed.

If your output csv file is not empty, we can assert the header was already written and simply append the row. Otherwise (file not exist or empty) we write the header before appending the row.

import os

defwrite_row_header_aware(filename, row):

    # in case file doesn't exist or is emptyifnot os.path.exists(filename) or os.stat(filename).st_size == 0:
        # write headerwithopen(filename, 'a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(['current_time', 'SHORTPERC', 'LONGPERC', ...])

    # write line as usualwithopen(filename, 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(row)
    
write_row_header_aware('data.csv', [current_time, SHORTPERC, LONGPERC, ...])

Solution 2:

Please make a check to know if the file exists, if it already exists use append to write rows to file else write the headers. By this way you could avoid writing headers multiple times. Please refer to this link

Post a Comment for "Csv Header In Python Only On The Top Row?"