问题:将列表的Python列表写入csv文件
我有一长串以下形式的清单-
a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]
即列表中的值是不同的类型-浮点数,整数,字符串。如何将其写入csv文件,以便输出的csv文件看起来像
1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2
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
回答 0
Python的内置CSV模块可以轻松处理此问题:
import csv
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a)
假设您的问题中的清单定义为a
。您可以通过各种可选参数来调整输出CSV的确切格式,csv.writer()
如上面链接的库参考页中所述。
Python 3更新
import csv
with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)
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.
Update for Python 3
import csv
with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)
回答 1
您可以使用pandas
:
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)
You could use pandas
:
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)
回答 2
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
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]])
official docs: http://docs.python.org/2/library/csv.html
回答 3
如果出于某种原因你想要做手工(不使用模块一样csv
,pandas
,numpy
等):
with open('myfile.csv','w') as f:
for sublist in mylist:
for item in sublist:
f.write(item + ',')
f.write('\n')
当然,滚动自己的版本可能容易出错且效率低下……这通常就是为什么要使用该模块的原因。但是有时编写自己的内容可以帮助您了解它们的工作原理,有时则更容易。
If for whatever reason you wanted to do it manually (without using a module like csv
,pandas
,numpy
etc.):
with open('myfile.csv','w') as f:
for sublist in mylist:
for item in sublist:
f.write(item + ',')
f.write('\n')
Of course, rolling your own version can be error-prone and inefficient … that’s usually why there’s a module for that. But sometimes writing your own can help you understand how they work, and sometimes it’s just easier.
回答 4
在我很大的列表中使用csv.writer花费了很长时间。我决定使用熊猫,它更快,更容易控制和理解:
import pandas
yourlist = [[...],...,[...]]
pd = pandas.DataFrame(yourlist)
pd.to_csv("mylist.csv")
好的部分,您可以更改一些内容以制作更好的csv文件:
yourlist = [[...],...,[...]]
columns = ["abcd","bcde","cdef"] #a csv with 3 columns
index = [i[0] for i in yourlist] #first element of every list in yourlist
not_index_list = [i[1:] for i in yourlist]
pd = pandas.DataFrame(not_index_list, columns = columns, index = index)
#Now you have a csv with columns and index:
pd.to_csv("mylist.csv")
Using csv.writer in my very large list took quite a time. I decided to use pandas, it was faster and more easy to control and understand:
import pandas
yourlist = [[...],...,[...]]
pd = pandas.DataFrame(yourlist)
pd.to_csv("mylist.csv")
The good part you can change somethings to make a better csv file:
yourlist = [[...],...,[...]]
columns = ["abcd","bcde","cdef"] #a csv with 3 columns
index = [i[0] for i in yourlist] #first element of every list in yourlist
not_index_list = [i[1:] for i in yourlist]
pd = pandas.DataFrame(not_index_list, columns = columns, index = index)
#Now you have a csv with columns and index:
pd.to_csv("mylist.csv")
回答 5
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_)
Ambers’s solution also works well for numpy arrays:
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_)
回答 6
如果您不想为此导入csv
模块,则可以仅使用Python内置组件将列表列表写入csv文件
with open("output.csv", "w") as f:
for row in a:
f.write("%s\n" % ','.join(str(col) for col in row))
If you don’t want to import csv
module for that, you can write a list of lists to a csv file using only Python built-ins
with open("output.csv", "w") as f:
for row in a:
f.write("%s\n" % ','.join(str(col) for col in row))
回答 7
确保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])
Make sure to indicate lineterinator='\n'
when create the writer; otherwise, an extra empty line might be written into file after each data line when data sources are from other csv file…
Here is my solution:
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])
回答 8
如何将列表列表转储到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]]]
>>>
How about dumping the list of list into pickle and restoring it with pickle module? It’s quite convenient.
>>> 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]]]
>>>
回答 9
在csv.writer函数中使用换行符跟随示例时,出现错误消息。以下代码对我有用。
with open(strFileName, "w") as f:
writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerows(result)
I got an error message when following the examples with a newline parameter in the csv.writer function. The following code worked for me.
with open(strFileName, "w") as f:
writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerows(result)