Save list of ordered tuples as CSV

Python, transposing a list and writing to a CSV file

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

output

1,4,7
2,5,8
3,6,9

Note that trying it in python 3 might give the error as mentioned in TypeError: a bytes-like object is required, not 'str' in python and CSV.

Consider to use with open('ur file.csv','w') as out: for python 3.


You can do this:

import csv

# note: If you use 'b' for the mode, you will get a TypeError
# under Python3. You can just use 'w' for Python 3

data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]

with open('ur file.csv','wb') as out:
    csv_out=csv.writer(out)
    csv_out.writerow(['name','num'])
    for row in data:
        csv_out.writerow(row)

    # You can also do csv_out.writerows(data) instead of the for loop

the output file will have:

name,num
"smith, bob",2
carol,3
ted,4
alice,5

Tags:

Python

Csv

Tuples