Still getting an error after using encode() when trying to write into a csv file

36 views Asked by At

Here's an example of the code:

import csv 
file = open("countries_information.csv", 'wb')
writer = csv.writer(file)
writer.writerow(['Country Name'.encode("utf-8)])

I get the error

"TypeError: a bytes-like object is required, not 'str'"

I've browsed online for a solution, but I'm at a loss.

2

There are 2 answers

1
Hira Arif On

Why aren't you specifying the format while opening the file? like:

import csv
file = open("countries_information.csv", 'w', encoding='utf-8')
writer = csv.writer(file)
writer.writerow(['Country Name'])
0
tdelaney On

It's not obvious from the documentation, but writerow doesn't work with binary files. The official documentation doesn't mention this as far as I know, but the built-in help says

Help on built-in function writerow:

writerow(...) method of _csv.writer instance
    writerow(iterable)
    
    Construct and write a CSV record from an iterable of fields.  Non-string
    elements will be converted to string.

Your binary data is converted to a string "b'Country Name'" and the fail happens when the string is written to the underlying binary file object. This happens in a C extension so the stack trace misses those critical calls.

On the positive side, you can do things like writerow([1,2,3]), but you've now seen the negative side.