16

I need to write into a csv file using python and each iterator item should start in a new line. So delimiter I am using is "\n". After each list has been written,next list should write from next cell. like below:

 lol = [[1,2,3],[4,5,6]]

The csv will be like:

1 4
2 5
3 6

What I have tried:

file = open("test.csv", "wb")
fileWriter = csv.writer(file , delimiter='\n',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow([1,2,3])
spamWriter = csv.writer(file , delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow([4,5,6])
file.close()

Which results like below:

 1
 2
 3
 4 5 6

Using csv module how can I get output like below:

 1 4 
 2 5
 3 6

here space means comma in a csv file.

Thanks.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234

3 Answers3

13

Without using zip, you could do this:

import csv

lol = [[1,2,3],[4,5,6],[7,8,9]]
item_length = len(lol[0])

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow([x[i] for x in lol])

This will output into test.csv:

1,4,7
2,5,8
3,6,9
redcurry
  • 2,381
  • 2
  • 24
  • 38
11

first transpose your input by using zip()

>>> zip(*lol)
[(1, 4), (2, 5), (3, 6)]

and after that just pass it to csw.writer e.g.

with open("test.csv", "wb") as f:
    fileWriter = csv.writer(f, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for row in zip(*lol):
        fileWriter.writerow(row)

... which results to:

$ cat test.csv 
1,4
2,5
3,6
Kimvais
  • 38,306
  • 16
  • 108
  • 142
4

If you are using Python3 you need to open files in text format "wt", more over csv has writerows that can be used to write everything at once. here is an example:

data=[("test", "value1", "value2"), ("test2", "value3", "value4")]
with open('my.csv','wt') as out:
   csv_out=csv.writer(out)
   csv_out.writerows(data)

I've just noticed that the question ask how to transform the list, that is a separate step and here is how I would do it:

lol = [[1,2,3],[4,5,6]]
data = zip(lol[0],lol[1])
Piotr Czapla
  • 25,734
  • 24
  • 99
  • 122