Skip to content Skip to sidebar Skip to footer

Save List Of Ordered Tuples As Csv

I have a list of tuples ordered by value. They are in the form (name,count) where count is number of occurrences for each unique name. I would like to take this list and transform

Solution 1:

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 3data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]

with open('ur file.csv','wb') asout:
    csv_out=csv.writer(out)
    csv_out.writerow(['name','num'])
    for row indata:
        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

Solution 2:

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

withopen('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i inrange(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.

Post a Comment for "Save List Of Ordered Tuples As Csv"