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


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")
        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.

There are few solutions of this problem –

Solution 1: Convert everything in 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.

Solution 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'.

Solution 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

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

modulenotfounderror: no module named ‘numpy’

Table of Contents Hide Installing numpyCheck Environment PATHReinstall Python and NumpyVirtual EnvironmentsRelated Posts: Python throws modulenotfounderror: no module named ‘numpy’, in four conditions – When you have multiple versions of…
View Post
python run bash script in background

python run bash script in background

Table of Contents Hide IntroductionTerminating background script after a timeoutHow to check if process is still running or terminated?How to get output from process?ConclusionLive DemoRelated Posts: Python subprocess library is…
View Post