Search code examples
stringpython-3.xio

Python3 - "a bytes-like object is required, not 'str'" on object of type <class 'bytes'>


the following piece of code causes me problems:

with open(fname, 'wb') as f:
    for p, values in params:
        s = str.encode("%s" % p)
        print("the type is:", type(s))
        print(s)
        print(s, file=f)

The output is:

the type is: <class 'bytes'>
b'myfancystring'
...
TypeError: a bytes-like object is required, not 'str'

So it is an object of type 'bytes' and still gives me this error? I am confused.

Thank you very much.

Greetings, Pfaeff


Solution

  • print always formats its inputs into a string before passing it to the file object's write() method, whether that file object is stdout (the default) or one you specify. This is why print(3) doesn't give you an error like "string expected but got int", and for that matter is why printing that byte string to the console didn't give you an error like "string expected but got bytes"

    Use the file object's write() method directly instead:

    f.write(b)