This tutorial will discuss the error
a bytes-like object is required, not 'str' in Python, and ways to fix it. This
TypeError shows when an invalid operation is done on the wrong data type.
We will discuss string and bytes objects in Python. Strings are a collection of characters, whereas the latter is a sequence of bytes, also called
Unicode objects. In Python3, all strings are
Unicode objects by default. In Python 2, we can convert strings to
Unicode and vice-versa using the
We get this error when working with a bytes object but treating it as a string. It is common due to the change of these objects in Python 2 and Python 3. We get this error while working with a binary file and treat it as a string.
with open('myfile.txt','rb') as f: a = f.read() print(type(a)) a.split(';')
TypeError: a bytes-like object is required, not 'str'
In the example above, we read a file in
rb mode. This mode means reading a binary file. The contents of this are bytes and stored in variable
a, and we display the type.
When we apply the
split() function to this variable, we get
a bytes-like object is required, not 'str' error. It’s because the
split() function works with string objects.
To avoid this error, beware of the data read type and its operations. We can also fix this error by converting the bytes-like object to string using the
with open('myfile.txt','rb') as f: a = str(f.read()) print(type(a)) s = a.split(';')
str() converts the object to a string to use the
This error is also frequent when working with sockets and sending or receiving data. We can use the
b character before a string to send bytes or the
encode() function with the
data = b'result' s.sendall(data)