How to fix TypeError: ‘str’ does not support the buffer interface with Python?

Sometimes, we want to fix TypeError: ‘str’ does not support the buffer interface with Python.

In this article, we’ll look at how to fix TypeError: ‘str’ does not support the buffer interface with Python.

How to fix TypeError: ‘str’ does not support the buffer interface with Python?

To fix TypeError: ‘str’ does not support the buffer interface with Python, we should call a file’s write method with bytes if the file is opened as a binary file.

For instance, we write

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")

with gzip.open(filename + ".gz", "wb") as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))

to call open the file with gzip.open as a writable binary file with 'wb'.

Then we call outfile.write with plaintext converted to bytes with bytes before writing it to the opened file.

Conclusion

To fix TypeError: ‘str’ does not support the buffer interface with Python, we should call a file’s write method with bytes if the file is opened as a binary file.