[英]Writing list of lists to csv file without any module/library
I've the following list of lists:我有以下列表:
l=[a,b,c,d]
where a,b,c,d are separate lists with different data types in each list.其中 a,b,c,d 是单独的列表,每个列表中具有不同的数据类型。
I'm trying to write each list as a separate column to the CSV file with headers as the name of the list.我正在尝试将每个列表作为单独的列写入 CSV 文件,并将标题作为列表的名称。
for ex:例如:
ab c d 1 a \pt ab c d 1 a \pt
I've tried the following approach: converted them to a zip我尝试了以下方法:将它们转换为 zip
l=zip(a,b,c,d)
and writing to CSV file:并写入 CSV 文件:
out = open('out.csv', 'w')
for row in l:
for column in row:
out.write('%s,' % column)
out.write('\n')
However, in this case, since one of the lists b
has text data, the separator, is not working and for that fact any separator being used in out.write('%s,' % column)
results in the wrong output.但是,在这种情况下,由于列表
b
中的一个具有文本数据,分隔符不起作用,因此在out.write('%s,' % column)
中使用的任何分隔符都会导致错误的 output。
Is there a way to solve this problem without using any modules?有没有办法在不使用任何模块的情况下解决这个问题?
This puts quote marks around each item:这会在每个项目周围加上引号:
for row in i:
out.write( '"' + '","'.join(row) + '"\n' )
However, the built-in csv
module is smarter, easy to use, and comes for free.但是,内置的
csv
模块更智能、易于使用且免费提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.