将 Python 列表列表写入 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14037540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:14:04  来源:igfitidea点击:

Writing a Python list of lists to a csv file

pythonfilecsvfile-iopython-2.7

提问by

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

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

1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

采纳答案by Amber

Python's built-in CSV modulecan handle this easily:

Python 的内置CSV 模块可以轻松处理此问题:

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.

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

Update for Python 3

Python 3 更新

import csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

回答by Dmitry Zagorulkin

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

官方文档:http: //docs.python.org/2/library/csv.html

回答by Semjon M?ssinger

Ambers's solution also works well for numpy arrays:

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_)

回答by Akavall

You could use pandas:

你可以使用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)

回答by tegan

If for whatever reason you wanted to do it manually (without using a module like csv,pandas,numpyetc.):

如果出于某种原因你想要做手工(不使用模块一样csvpandasnumpy等):

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.

当然,滚动您自己的版本可能容易出错且效率低下……这通常是有一个模块的原因。但有时自己编写可以帮助您了解它们的工作原理,有时会更容易。

回答by yashi wang

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

确保lineterinator='\n'在创建作者时指明;否则,当数据源来自其他 csv 文件时,可能会在每个数据行之后将额外的空行写入文件...

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])

回答by Dinidiniz

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:

在我非常大的列表中使用 csv.writer 花了很长时间。我决定使用pandas,它更快更容易控制和理解:

 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:

您可以更改某些内容以制作更好的 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")

回答by Good Will

How about dumping the list of list into pickle and restoring it with pickle module? It's quite convenient.

如何将列表列表转储到 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]]]
>>> 

回答by yellow01

If you don't want to import csvmodule for that, you can write a list of lists to a csv file using only Python built-ins

如果您不想为此导入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))

回答by Jie

I got an error message when following the examples with a newlineparameter in the csv.writer function. The following code worked for me.

在 csv.writer 函数中使用换行符参数执行示例时,我收到一条错误消息。以下代码对我有用。

 with open(strFileName, "w") as f:
    writer = csv.writer(f, delimiter=',',  quoting=csv.QUOTE_MINIMAL)
    writer.writerows(result)