简体   繁体   中英

How do I write a list of strings to a CSV file, with each item of the list on a new row?

I have a list of strings as follows:

sentence = ['this stuff', 'is not','that easy']

And I want to write to a csv file, with each item in the list on a different line.

When I use the code below,

with open(os.path.join(path, 'testlist.csv'), 'w') as my_file:
    f_writer = csv.writer(my_file)
    f_writer.writerow(sentence)

I get the following as output:

this stuff,is not,that easy

How do I get each item of the list on a different row?

write row take a list and writes it in one row separated by , if you want the elements of the row on separate lines

pass them one by one

sentence = ['this stuff', 'is not','that easy']
with open(os.path.join(path, 'testlist.csv'), 'w') as my_file:
    f_writer = csv.writer(my_file)
    for s in sentence: f_writer.writerow([s])
    # f_writer.writerow(sentence)

Since others have given you some answers, here you go in Python 3.x:

print (*sentence,sep='\n',file=open(os.path.join(path, 'testlist.csv'), 'w'))

or in Python 2.7 you could do:

print open(os.path.join(path, 'testlist.csv'), 'w'),"\n".join(sentence)

(neither of the above need the csv module)

In your example, I think you can just change

f_writer = csv.writer(my_file)

to

f_writer = csv.writer(my_file, delimiter='\n')

And in a real stretch, you could probably instead change:

 f_writer.writerow(sentence)

to

 f_writer.writerows(list([x] for x in sentence))

Happy Pythoning!

This works:

import pandas as pd
sentence = ['this stuff', 'is not','that easy']
sent = pd.Series(sentence)
sent.to_csv('file.csv', header = False)

1) Use lists within the "sentence"

2) Replace "writerow" with "writerows"

Eg:

# Change 1
sentence = [['this stuff'], ['is not'],['that easy']]

with open(os.path.join(path, 'testlist.csv'), 'w') as my_file:
    f_writer = csv.writer(my_file)
# Change 2
    f_writer.writerows(sentence)

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