[英]How to print nested list as new line in CSV?
嵌套列表:
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']]
列表中的嵌套列表表示要在 CSV 中添加的新行
CSV 文件中所需的输出是:
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!
我尝试了以下方法:
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])
我获得的输出不反映记录的新列,而它将新列表的所有新记录压缩到 AIS_Type 下的单个列中。 因此,我希望它以 分隔,并将每个相关数据引用到右列。
问题是您的所有列表都只有一个值。
您应该将它们['Unknown','Unknown','-','-','9127057']
实际列表, ['Unknown','Unknown','-','-','9127057']
或者这样做:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.