TypeError: write() argument must be str, not bytes (Python)

Python provides several functions for opening, closing, and appending strings or bytes to a file. The file must be opened in a specific mode to perform operations on that file. There are several file modes, such as “a” mode for appending, and “w” mode indicates that the text file is opened for writing, etc. Sometimes opening files for writing bytes in incorrect mode shows the “write() argument must be str, not bytes” error in Python.

This write-up will provide a detailed guide on resolving the “TypeError: write() argument must be str, not bytes” in Python. This guide will cover the following concepts:

So, let’s begin with the first reason.

Reason: Opening File in “w” Mode for Writing Bytes

The prominent reason which causes this error is when a user tries to open the file in “w” mode for writing bytes in Python. The below snippet shows how this error occurs:

The above snippet shows “TypeError” because the file “itslinuxfoss.txt” is open in “w” mode for writing the bytes.

Solution 1: Open the File in “wb” Mode

To fix this error, we need to open the file in “wb” mode rather than “w” mode for writing bytes to a file. The correct code block is shown below:

Code:

with open('itslinuxfoss.txt', 'wb') as f:
    f.write(b'hello!')
    f.write(b'welcome')
    f.write(b'Python Guide')

In the above code:

  • The “open()” function is utilized to open the file “itslinuxfoss.txt” file.
  • The file name is passed as the first argument while “wb” mode is passed as a second argument to the open() function.
  • The “write()” function is used to write various lines of bytes in a file.

Output:

The output snippet proves that opening the desired file in the “wb” mode resolves the stated error.

Solution 2: Decoding the Byte Object into String

This error can also be resolved using the decoding approach instead of opening the file in “wb” mode. Here is an example code:

with open('itslinuxfoss.txt', 'w', encoding='utf-8') as f:
    f.write(b'Python Guide'.decode('utf-8'))

In the above code, the file “itslinuxfoss.txt” is opened in “w” mode and uses the standard encoding “utf-8” to encode the file. The “bytes.decode()” function is used to decode the input bytes “Python Guide” into the string.

Output:

The output shows that the bytes object has been decoded into the string using the “bytes.decode()” function.

Note: To write a string to a text file in Python, you can read the following article.

That’s it from this guide!

Conclusion

The “write() argument must be str, not bytes” error appears when a user tries to open the file in “w” mode for writing bytes in Python. To resolve this error, open the file in “wb” mode, or use the decoding approach to decode the bytes into a string. This post presented a detailed guide on resolving Python’s “write() argument must be str, not bytes” error.