Chadmeistr
Chadmeistr

Reputation: 47

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?

Upvotes: 0

Views: 84

Answers (4)

Breno Monteiro
Breno Monteiro

Reputation: 101

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)

Upvotes: 0

RufusVS
RufusVS

Reputation: 4127

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!

Upvotes: 1

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

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)

Upvotes: 1

Saurabh Jain
Saurabh Jain

Reputation: 1712

This works:

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

Upvotes: 0

Related Questions