如何使用带有新行的python将列表保存为.csv文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29310792/
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-19 04:22:32  来源:igfitidea点击:

How to save a list as a .csv file with python with new lines?

pythonlistpython-2.7csvpandas

提问by skwoi

I would like to save a python list in a .csvfile, for example I have a list like this:

我想在.csv文件中保存一个 python 列表,例如我有一个这样的列表:

['hello','how','are','you']

I would like to save it like this:

我想像这样保存它:

colummn,
hello,
how,
are,
you,

I tried the following:

我尝试了以下方法:

myfile = open('/Users/user/Projects/list.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL,'\n')
wr.writerow(pos_score)

采纳答案by grechut

use pandas to_csv(http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_csv.html)

使用熊猫to_csvhttp://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_csv.html

>>> import pandas as pd
>>> df = pd.DataFrame(some_list, columns=["colummn"])
>>> df.to_csv('list.csv', index=False)

回答by EdChum

You can just pass this as the value of a dict with key 'column' to a DataFrame constructor and then call to_csvon the df:

您可以将其作为键为“column”的 dict 的值传递给 DataFrame 构造函数,然后调用to_csvdf:

In [43]:

df = pd.DataFrame({'column':['hello','how','are','you']})
df
Out[43]:
  column
0  hello
1    how
2    are
3    you
In [44]:

df.to_csv()
Out[44]:
',column\n0,hello\n1,how\n2,are\n3,you\n'

回答by Padraic Cunningham

If you want all the words on different lines you need to set the deliiter to \n:

如果您想要不同行上的所有单词,则需要将分隔符设置为\n

l = ['hello','how','are','you']
import  csv

with open("out.csv","w") as f:
    wr = csv.writer(f,delimiter="\n")
    wr.writerow(l)

Output:

输出:

hello
how
are
you

If you want a trailing comma:

如果你想要一个尾随逗号:

with open("out.csv","w") as f:
    wr = csv.writer(f,delimiter="\n")
    for ele in l:
        wr.writerow([ele+","])

Output:

输出:

hello,
how,
are,
you,

I would recommend just writing the elements without the trailing comma, there is no advantage to having a trailing comma but may well cause you problems later.

我建议只写不带尾随逗号的元素,尾随逗号没有任何好处,但很可能在以后给你带来问题。