Reputation: 35
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
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