user11410690
user11410690

Reputation: 35

Save tuple into csv

I am trying to save my tuple list into csv, but I get an Error: a bytes-like object is required, not 'str'

import csv

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']) # here I'm getting the Error
    for row in data:
        csv_out.writerow(row)

I expect a csv file with header name and num with the tuple "data"

Upvotes: 0

Views: 108

Answers (1)

Alexander Keller
Alexander Keller

Reputation: 46

You've opened the file in binary mode. The csv library works with files using string objects.

with open('ur file.csv', 'w') as out:

You could also simplify and speed it up using writerows instead of looping over it and doing writerow yourself.

import csv

data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]
data.insert(0, ('Name', 'Number'))

with open('file.csv','w') as out:
    csv.writer(out).writerows(data)

Upvotes: 1

Related Questions