文章内容
2017/8/20 14:14:56,作 者: 黄兵
解决Writing a Python list of lists to a csv file
和c语言一样,不能使用'rw'方式打开一个文件并进行读写,正确的方式是‘r+’,详见http://mail.python.org/pipermail/python-bugs-list/2001-May/005216.html Bu
I have a long list of lists of the following form ---
a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]
i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like
1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2
Python 有很好的文本分析和处理能力,所以我想到,Python的文件类型file是内建类型 然后就是实例和创建函数楼(构造函数) open函数的两个参数 文件位置 打开方
answer 1 >>解决方法
Python's built-in CSV module can handle this easily:
import csv
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a)
This assumes your list is defined as a
, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer()
as documented in the library reference page linked above.
评论列表