Reputation: 451
I have this list of countries:
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
I'm trying to write this into a csv:
with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write)
csvout.writerow(country)
output_write.close()
However the output puts the values into a row rather than a column in csv. Can someone please let me know how to change it?
Thanks in advance!
I followed some of the suggestions below and the output has empty lines between rows:
The code I used:
import csv
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write)
for item in country:
csvout.writerow((item, ))
Update:
I figured the reason that I'm getting an empty line because each row is because windows interpret a new line differently. The code that finally work for me is:
import csv
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'w', newline = '') as output_write:
csvout = csv.writer(output_write)
for item in country:
csvout.writerow((item, ))
Found a related post regarding the empty row:
Upvotes: 2
Views: 1514
Reputation: 2003
Try the following:
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write, lineterminator='\n')
for item in country:
csvout.writerow((item, ))
Upvotes: 1
Reputation: 2622
Try this:
import csv
countries = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'w') as output_write:
csvout = csv.writer(output_write, lineterminator='\n')
for country in countries:
csvout.writerow([country])
Upvotes: 1
Reputation: 7151
You have to iterate through the list if you want to write each item to a separate line:
import csv
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write, delimiter=',')
for c in country:
csvout.writerow([c])
Upvotes: 2