51

I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in test_list:
        writer.writerow([val])

If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?

1
  • Fundamentally, CSV writes rows, not columns, and is conceptually a rows (which then contain columns), not the other way around. Hence the name of the method writerow. So really the question is how to get the necessary rows, given data which is in columns - which is a duplicate. Commented Oct 11, 2024 at 7:28

7 Answers 7

69

Change them to rows:

rows = zip(list1, list2, list3, list4, list5)

Then just:

import csv

with open(newfilePath, "w") as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)
Sign up to request clarification or add additional context in comments.

3 Comments

I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?
Thanks Joran! This helped me a lot, because I am not able to use Pandas.
Ok, this way its pretty "simple". What could i do if there is a bunch of lists with 1...n endings. Is there a way to combine zip and a loop threw all of the lists?
37

The following code writes python lists into columns in csv

import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
      wr = csv.writer(myfile)
      wr.writerow(("List1", "List2"))
      wr.writerows(export_data)
myfile.close()

The output looks like this

enter image description here

1 Comment

For python 2.7 use from itertools import izip_longest as zip_longest and newline=''" will throw error for python 2.7 . To avoid this error , open the file in 'wb' mode instead of 'w' mode. This will eliminate the need for newline
6

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

Comments

5

You can use izip to combine your lists, and then iterate them

for val in itertools.izip(l1,l2,l3,l4,l5):
    writer.writerow(val)

1 Comment

It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...
2

I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:

import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(("list1", "list2"))
    rcount = 0
    for row in list1:
        wr.writerow((list1[rcount], list2[rcount]))
        rcount = rcount + 1
    myfile.close()

Comments

2

I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.

 writer.writerow(("ColName1", "ColName2", "ColName"))
                 for i in range(len(first_col_list)):
                     writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))

Comments

0
import csv
dic = {firstcol,secondcol} #dictionary
csv = open('result.csv', "w") 
for key in dic.keys():
    row ="\n"+ str(key) + "," + str(dic[key]) 
    csv.write(row)

1 Comment

Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.