Search code examples
pythonlistcsvexport-to-csvopencsv

Create a csv file in from a python list


I have a list like the following with the \n separating each new lines

['Data,9,record,timestamp,"896018545",s,position_lat,"504719750",semicircles,position_long,"-998493490",semicircles,distance,"10.87",m,altitude,"285.79999999999995",m,speed,"1.773",m/s,unknown,"3929",,unknown,"1002",,enhanced_altitude,"285.79999999999995",m,enhanced_speed,"1.773",m/s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\n', 'Data,9,record,timestamp,"896018560",s,position_lat,"504717676",semicircles,position_long,"-998501870",semicircles,distance,"71.85",m,altitude,"285.0",m,speed,"5.533",m/s,unknown,"3924",,unknown,"1001",,enhanced_altitude,"285.0",m,enhanced_speed,"5.533",m/s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]

This is hard to read, so I need to extract the following out of this list into a CSV file in python in the below format without using pandas:

timestamp, position_lat,altitude
"896018545","504719750","285.79999999999995"
"896018560","504717676","285.0"

I have the following, but I am confused about how to add the data into the CSV file:

header = ['timestamp','latitude','altitude']
with open('target.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)
    # write the header
    writer.writerow(header)
    # write the data

Solution

  • If I'm understanding your question correctly, all you need to do is write additional rows that include your data.

    ...
        ...
        writer.writerow(["896018545","504719750","285.79999999999995"])
        writer.writerow(["896018560","504717676","285.0"])
    
    # alternatively,
    
    data = [["896018545","504719750","285.79999999999995"], 
    ["896018560","504717676","285.0"]]
    ...
        ...
        for row in data:
            writer.writerow(row)