[英]How to write list contents to csv file as a single row
I have the following sample list: 我有以下示例列表:
sample_list = [['test1', 'test2'], ['am', 'cm']]
I want to write the above list to csv
file. 我想将以上列表写入
csv
文件。 I'm using the following code for this: 我为此使用以下代码:
with open('sample.csv', 'wb') as f_csv:
writer = csv.writer(f_csv, delimiter=',', dialect='excel')
writer.writerows(sample_list)
f_csv.close()
The issue is that when I open sample.csv
I see that test1
, test2
are stored in separate columns, same for am
, cm
(stored in next row) 问题是,当我打开
sample.csv
我看到test1
, test2
存储在单独的列中,与am
, cm
相同(存储在下一行中)
I need output in following form: Each sub-list to be listed in separate row and elements of sub-list in one column. 我需要以下形式的输出:每个子列表在单独的行中列出,并且子列表的元素在一列中。
test1,test2
am,cm
Please can you help me in where i'm going wrong. 请帮我解决我的问题。
You need to change your list to include the comma ,
as a value in the converted string contents , if the list values can be of type int
, convert them and then create the strings from the lists: 你需要改变你的列表,包括逗号
,
因为在转换后的字符串内容的值,如果列表中的值可以是类型的int
,将它们转换,然后创建一个从列表中的字符串:
sample_list = [[",".join([str(item) for item in sub])] for sub in sample_list]
If we add a number to your original list, so: 如果我们将数字添加到您的原始列表中,那么:
sample_list = [['test1', 'test2', 392], ['am', 'cm']]
After the list comprehension, the list will be of the form: 理解列表之后,列表将具有以下形式:
sample_list = [['test1,test2,392'], ['am,cm']]
Then, call writerows()
on this list of lists: 然后,在此列表列表上调用
writerows()
:
with open('sample.csv', 'wb') as f_csv:
writer = csv.writer(f_csv, delimiter=',', dialect='excel')
writer.writerows(sample_list)
The output in sample.csv
will be of the form: sample.csv
的输出将具有以下形式:
"test1,test2,392"
"am,cm"
Ps You don't need to close f_csv
. Ps您不需要关闭
f_csv
。 Using it with the with
keyword takes care of that automatically. 与
with
关键字一起使用可自动解决此问题。
The following script should produce one column per row: 以下脚本应每行产生一列:
import csv
sample_list = [['test1', 'test2', 1, 2], ['am', 'cm', 3, 4]]
with open('sample.csv', 'wb') as f_csv:
writer = csv.writer(f_csv, dialect='excel')
for sample in sample_list:
writer.writerow([','.join(map(str, sample))])
Which creates a file as follows: 这将创建一个文件,如下所示:
"test1,test2,1,2"
"am,cm,3,4"
When opened in Excel, this would give one column. 在Excel中打开时,将显示一列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.