将Python列表列表写入csv文件 [英] Writing a Python list of lists to a csv file

查看:256
本文介绍了将Python列表列表写入csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长列表的列表如下形式---

  a = [[1.2,'abc' ,3],[1.2,'werew',4],........ [1.4,'qew',2]] 

ie列表中的值是不同的类型 - float,int,strings.How如何将其写入csv文件,以便我的输出csv文件看起来像

  1.2,abc,3 
1.2,werew,4



1.4,qew,2


解决方案

-in CSV模块可以轻松处理此问题:

  import csv 

with open(output.csv,wb)as f:
writer = csv.writer b $ b writer.writerows(a)

这假设你的列表被定义为 a ,因为它在你的问题。您可以通过各种可选参数调整输出CSV的确切格式,如上面链接的库参考页中所述 csv.writer()

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'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.

这篇关于将Python列表列表写入csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆