PaperRockBazooka
PaperRockBazooka

Reputation: 167

How to turn a list into a column in a csv?

Currently I have a populated list

list =[a, b, c, d]

I want to convert the content of the list to a csvfile and have all of the elements of the list be one column. This is the current code I have:

with open('twitter3.csv', 'w+') as csvfile:
    writer = csv.writer(csvfile, dialect='excel')
    writer.writerow(list)

The outputted csv file contains the elements of the list but as the method implies, it has written all the contents within the first row.

I have tried making a for loop to write each element + \n but the writerow method has an issue with that (puts commas after each letter), and there is no writecolumn method for a csvwriter.

Upvotes: 2

Views: 2599

Answers (4)

Cedric Zoppolo
Cedric Zoppolo

Reputation: 4743

To perform this task I would use pandas package as follows:

import pandas as pd
l=["a","b","c","d"]
df=pd.DataFrame(l)
df.to_csv("twitter3.csv", index=False,header=False)

pandas is also great to read csv and even work with Excel files.

Upvotes: 4

yoonghm
yoonghm

Reputation: 4655

I put all the code in one place, so that can copy and test it out.

import csv

# Should not use 'list' as variable
lst =['a', 'b', 'c', 'd']

# newline='' prevent additional new lines in file
with open('twitter3.csv', 'w+', newline='') as csvfile:
  writer = csv.writer(csvfile, dialect='excel')
  for l in lst:
    writer.writerow(l)

Output twitter3.csv is then:

a
b
c
d

Upvotes: 0

martineau
martineau

Reputation: 123531

This is about the simplest way I can think of to do it:

import csv

my_list = ['a', 'b', 'c', 'd']

with open('twitter3.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='excel')
    writer.writerows(tuple(item) for item in my_list)

Note I changed the name of your list variable to my_list so it wouldn't conflict with the built-in list class.

Upvotes: 1

Henry
Henry

Reputation: 15732

You can do this by joining the elements of your list into a single string with new line characters '\n\r' as the separators, then write the whole string to your file.

For example:

my_list = [a, b, c, d]

with open("twitter3.csv", "w+") as csvfile:
    to_write = "\n\r".join(my_list)
    csvfile.write(to_write)

(Also '\n' works)

Upvotes: 0

Related Questions