Typeerror: write argument must be str not bytes

In this article, we will discuss on how to fix the error message typeerror write argument must be str not bytes.

The typeerror: write argument must be str not bytes error typically occurs if you are trying to write bytes to a file without opening the file in wb mode.

Why we get TypeError: write() argument must be str, not bytes?

We get TypeError: write() argument must be str, not bytes because when we try to write binary data to a text file or a stream that expects a string.

Here an example on how the error occur:

with open('file.txt', 'w') as file:
    file.write(b'hello')

Output:

Traceback (most recent call last):
File “C:\Users\Dell\PycharmProjects\pythonProject\main.py”, line 2, in
file.write(b’hello’)
TypeError: write() argument must be str, not bytes

The example code is causing an error because it is trying to write a byte string (b’hello’) to a text file opened in write mode (‘w’).

When a file is opened in write mode, it expects to receive a string as input, not bytes.

Also, read the other related articles about argument:

typeerror ‘encoding’ is an invalid keyword argument for this function

How to fix this error write argument must be str not bytes?

Here are the following solutions to fix this error write argument must be str not bytes.

Solution 1: Open the file in binary mode (‘wb’) instead of text mode

To solve the error write argument must be str not bytes, we need to open the file in binary mode (‘wb’) instead of text mode.

For example:

with open('file.txt', 'wb') as file:
    file.write(b'hello')

Solution 2: Encode the byte string as a string before writing it to the file

Another solution to solve the error is to encode the byte string as a string before writing it to the file.

For example:

with open('file.txt', 'w') as file:
    file.write(b'hello'.decode('utf-8'))

The ‘b’ before the string ‘hello’ shows that it is a bytes object, which is decoded using the ‘utf-8’ encoding to convert it into a string before writing it to the file.

Solution 3: Using the rb (read binary) mode

The other way to solve the error is using the rb (read binary) mode.

For example:

with open('file.txt', 'rb') as file:
    lines = file.readlines()
    print(lines)

    first_value = lines[0].decode('utf-8')

It will reads all the lines in the file using the readlines() method and stores them in the lines variable.

Conclusion

In conclusion, by following the solutions in this article it will be able to help you to resolved the typeerror: write argument must be str not bytes .

FAQs

What is a bytes object?

A bytes object is a sequence of bytes that represents binary data. Each byte is represented as an integer value between 0 and 255.

How do I specify the mode in Python’s open() function?

You can specify the mode when you open a file in Python using the “mode” parameter. For example, to open a file in binary mode, you would use the “wb” flag.