我有一长串这样的表格——
a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]
也就是说,列表中的值是不同类型的——float,int, strings。我如何将它写入csv文件,使我的输出csv文件看起来像这样
1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2
我有一长串这样的表格——
a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]
也就是说,列表中的值是不同类型的——float,int, strings。我如何将它写入csv文件,使我的输出csv文件看起来像这样
1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2
当前回答
如何转储列表的列表到pickle和恢复它与pickle模块?这很方便。
>>> import pickle
>>>
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
... pickle.dump(mylist, f)
>>> with open('mylist', 'rb') as f:
... mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>>
其他回答
你可以用熊猫:
In [1]: import pandas as pd
In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]
In [3]: my_df = pd.DataFrame(a)
In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)
Ambers的解决方案也适用于numpy数组:
from pylab import *
import csv
array_=arange(0,10,1)
list_=[array_,array_*2,array_*3]
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(list_)
如何转储列表的列表到pickle和恢复它与pickle模块?这很方便。
>>> import pickle
>>>
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
... pickle.dump(mylist, f)
>>> with open('mylist', 'rb') as f:
... mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>>
确保在创建写入器时指明lineterinator='\n';否则,当数据源来自其他CSV文件时,可能会在每个数据行后写入额外的空行…
以下是我的解决方案:
with open('csvfile', 'a') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for i in range(0, len(data)):
spamwriter.writerow(data[i])
import csv
with open(file_path, 'a') as outcsv:
#configure writer to write standard csv file
writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
writer.writerow(['number', 'text', 'number'])
for item in list:
#Write item to outcsv
writer.writerow([item[0], item[1], item[2]])
官方文档:http://docs.python.org/2/library/csv.html