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
DDDOriginal
2024-11-26 12:06:12683browse

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'))

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)

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!

Statement:
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