将 Python 列表列表写入 csv 文件 [英] Writing a Python list of lists to a csv file
本文介绍了将 Python 列表列表写入 csv 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一长串以下形式的列表---
I have a long list of lists of the following form ---
a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]
即列表中的值是不同类型的——float、int、strings.如何将其写入 csv 文件,以便我的输出 csv 文件看起来像
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 的内置 CSV 模块可以轻松处理:
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)
这假设您的列表被定义为 a
,因为它在您的问题中.您可以通过 csv.writer()
的各种可选参数调整输出 CSV 的确切格式,如上面链接的库参考页面中所述.
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.
Python 3 更新
import csv
with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)
这篇关于将 Python 列表列表写入 csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文