简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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