vivi11130704
vivi11130704

Reputation: 451

Python Write a list into csv, can't put values into a column

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:

enter image description here

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:

python empty row

Upvotes: 2

Views: 1514

Answers (3)

Arun
Arun

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

SKN
SKN

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

enter image description here

Upvotes: 1

Foxan Ng
Foxan Ng

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

Related Questions