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

Question:

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.

Asked By: PaperRockBazooka

||

Answers:

You can do this by joining the elements of your list into a single string with new line characters 'nr' 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 = "nr".join(my_list)
    csvfile.write(to_write)

(Also 'n' works)

Answered By: Henry Woody

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
Answered By: yoonghm

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.

Answered By: martineau

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.

Answered By: Cedric Zoppolo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.