Home > Backend Development > Python Tutorial > How to Resolve TypeError: \'str\' Does Not Support the Buffer Interface in Python 3 When Compressing Text?

How to Resolve TypeError: \'str\' Does Not Support the Buffer Interface in Python 3 When Compressing Text?

DDD
Release: 2024-11-26 12:06:12
Original
737 people have browsed it

How to Resolve TypeError: 'str' Does Not Support the Buffer Interface in Python 3 When Compressing Text?

TypeError: 'str' Does Not Support the Buffer Interface

Utilizing Python3, you may encounter this error due to the distinct handling of strings compared to Python2. To resolve this issue, you must encode the string into bytes.

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'))
Copy after login

In Python3, strings are not identical to those in Python2, necessitating the use of the bytes() function. Additionally, consider avoiding variable names like "string" or "file" since they are already defined as functions or modules.

For comprehensive text compression, including non-ASCII characters, the code provided utilizes UTF-8 encoding to ensure the integrity of Polish letters.

plaintext = 'Polish text: ąćęłńóśźżĄĆĘŁŃÓŚŹŻ'
filename = 'foo.gz'
with gzip.open(filename, 'wb') as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))
with gzip.open(filename, 'r') as infile:
    outfile_content = infile.read().decode('UTF-8')
print(outfile_content)
Copy after login

The above is the detailed content of How to Resolve TypeError: \'str\' Does Not Support the Buffer Interface in Python 3 When Compressing Text?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template