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