TypeError: a bytes-like object is required, not ‘str’ Python – Code Example

Total
0
Shares

Python3 throws the TypeError: a bytes like object is required, not ‘str’, when we try to do string operations on binary values. It generally appears when you open a file in binary mode. Consider this code –

with open("superhero.txt", 'rb') as myFile:
    lines = [x.strip() for x in myFile.readlines()]

In this code, we are opening superhero.txt file in 'rb' mode, which means that it is read only and binary. Now suppose we do operations like string find, then that will fail because we have binary data and not string data.

for line in lines:
    singleLine = line.strip().lower()
    if 'captain america' in singleLine:
        print("Found Captain")
    else:
        print("Missing Captain")

This piece of code will fail on line if 'captain america' in singleLine: . This is because in is used for comparing string 'captain america' with singleLine which is holding binary data.

Solutions with Code Examples

1: Convert everything to binary

One solution is to convert the string to binary so that binary is compared with another binary. That will work. So, this code is fine –

if b'captain america' in singleLine:

Here we are type casting 'captain america' to binary using b. Since both are binary now so there will not be issues.

2: Open file in text mode

If there is no particular requirement to open a file in binary, then you should open it in text mode. Check this code –

with open("superhero.txt", 'r') as myFile:

To open a file in text mode, simply change 'rb' to 'r'.

3: Decode binary to string

You can also use the decode() function to convert binary value to string counterpart. This approach is useful in case when you need to open the file in binary but still have to do some string operations. Check out the below code –

with open("superhero.txt", 'rb') as myFile:
    lines = [x.decode('utf8').strip() for x in myFile.readlines()]

    Tweet this to help others

Live Demo

Open Live Demo