Home > Blockchain >  How can i put the header only once on top of the file?
How can i put the header only once on top of the file?

Time:03-24

i want to put the header in the first row, the the data will be in the next row but the header keep repeating. can anyone help me fixing my programming?

here is my programme

`if str(raw_data\[0:6\]) == "b'$GNRMC'":
lat = parsed_data.lat
lon = parsed_data.lon

        t2 = time.time()        
        elapsed_time = t2 - t1
        gps = [str(elapsed_time), str(lat), str(lon)]
        
        header = ['Time', 'Latitude', 'Longitude']
    
        with open('C:/Desktop/GPS_Trial/9.csv', 'a', newline = '', encoding='UTF8') as f:
            writer = csv.writer(f)
            writer.writerow(header)
            writer.writerow(gps)
            print(gps)`

CodePudding user response:

Before write to a file, check if the file exists.

filename = 'C:/Desktop/GPS_Trial/9.csv'
rows_to_be_written = []
if not os.path.exists(filename):
    rows_to_be_written.append(header)
rows_to_be_written.append(gps)

with open(filename, 'a', newline='', encoding='UTF8') as f:
    writer = csv.writer(f)
    for row in rows_to_be_written:
        writer.writerow(row)
  • Related