简体   繁体   English

将列表导出为一列中的 CSV

[英]Exporting list to CSV in one column

I want to export a list to csv in a single column with each entry starting a new line.我想在单个列中将列表导出到 csv,每个条目都开始一个新行。

My list is like:我的清单是这样的:

['Jimmy French', 'Casey Fryer', 'Jane Pickens', 'Tommy L. Garcetti', 'Nada Lewis']

Following another stack overflow question, my code reads:在另一个堆栈溢出问题之后,我的代码如下:

with open("export_5.csv","w") as f:
    w = csv.writer(f, lineterminator=',')
    w.writerow(phone_names_value_list)

The output is:输出是:

Jimmy French,Casey Fryer,Jane Pickens,Tommy L. Garcetti,Nada Lewis,

Is this because I am viewing it in notepad?这是因为我在记事本中查看它吗? Is there something I should change to make it print in one column?有什么我应该改变以使其在一列中打印的吗?

**Also, how might I remove the comma? **另外,我该如何删除逗号?

you can write it like this:你可以这样写:

with open("export_5.csv","w") as f:
    w = csv.writer(f, lineterminator='\n')
    for item in phone_names_value_list:
        w.writerow([item])

or with pandas you can do it like:或者使用熊猫你可以这样做:

import pandas as pd
a=['Jimmy French', 'Casey Fryer', 'Jane Pickens', 'Tommy L. Garcetti', 'Nada Lewis']
df=pd.DataFrame(a)
df.to_csv('output_file.csv', index=False,header=None)

A single column csv is a plain text file with one field per line.单列 csv 是一个纯文本文件,每行一个字段。 Just print that.打印那个就行了。

Possible code:可能的代码:

with open("export_5.csv","w") as f:
    for field in phone_names_value_list:
        print(field, file=f)

The only problem in above code, it that nothing guarantees that the lines will be ended with \\r\\n as proper csv files should be.上面代码中唯一的问题是,不能保证行将以\\r\\n结尾,因为正确的 csv 文件应该是这样。 If it matters, you will have to explicitely write them in binary mode:如果重要,您将必须明确地以二进制模式编写它们:

with open("export_5.csv","bw") as f:
    for field in phone_names_value_list:
        print(field.encode() + b'\r\n', file=f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM