Nested List:
AIStable = [['Unknown,Unknown,-,-,9127057/-,-,-,-,0.0°/0.0kn,0.0S/0.0W,-'], ['Tanker,MarshallIslands,USHOU>DOSPM,Jan3,19:00,9683984/538005270,V7CJ5,183/32m,11.4m,112.0°/12.8kn,18.26069N/75.77137W,Jan2,202006:47UTC'], ['Productisnotfound!'], ['Productisnotfound!'], ['Productisnotfound!'], ['Productisnotfound!'], ['Cargoship,Russia,VLADIVOSTOK,RUSSIA,Dec31,00:00,9015785/273213710,UBCT2,119/18m,5.6m,7.9°/0.0kn,43.09932N/131.88229E,Jan1,202009:06UTC'], ['Tanker,Singapore,YEOSU,SK,Jan1,03:00,9370991/566376000,9V3383,100/16m,4.3m,188.0°/0.1kn,34.72847N/127.81362E,Jan2,202007:41UTC'], ['Cargoship,Italy,QINGDAO,Jan1,02:00,9511454/247283400,ICAH,292/45m,18.2m,324.0°/5.4kn,27.80572N/125.07295E,Jan2,202007:20UTC']]
Nested list within the list signifies a new line to be added in the CSV
The desired output in the CSV file is:
AIS_Type Flag Destination ETA IMO/MMSI Callsign Length/Beam Current_Draught Course/Speed Coordinates Last_Report
Unknown Unknown - - 9127057/- - - - - 0.0°/0.0kn 0.0S/0.0W -
Tanker MarshallIslands USHOU>DOSPM Jan3 19:00 9683984/538005270 V7CJ5 183/32m 11.4m 112.0°/12.8kn 18.26069N/75.77137W Jan2 202006:47UTC
Product is not found!
I tried the following:
AISUpdated = [[''.join(','.join(i).split())] for i in AIStable]
print(AISUpdated)
filename = "vesselsUpdated.csv"
with open(filename, 'w' , newline = '') as f:
writer = csv.writer(f,delimiter = ",")
headers = "AIS_Type,Flag,Destination,ETA,IMO/MMSI,Callsign,Length/Beam,Current_Draught,Course/Speed,Coordinates,Last_Report"
f.write(headers)
writer.writerows("\n")
for i in AISUpdated:
writer.writerows([i])
The output i obtain does not reflect a new column for the records while it squeeze all the new records of the new list to one single column under AIS_Type. Hence, i want it to separate by , and referencing each relevant data to the right column.
The problem is that all your lists only have one value.
You should either make them an actual lists, ['Unknown','Unknown','-','-','9127057']
or do it like this:
AISUpdated = [i[0].split(',') for i in AIStable]
with open('file.csv','w') as f:
writer = csv.writer(f)
writer.writerow(headers.split(','))
writer.writerows(AISUpdated)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.