0

I keep getting this error "TypeError: 'str' does not support the buffer interface" Not sure what is going wrong. Any assistance would be great.

import zlib
#User input for sentnce & compression.
sentence = input("Enter the text you want to compress: ")
com = zlib.compress(sentence)
#Opening file to compress user input.
with open("listofwords.txt", "wb") as myfile:
    myfile.write(com)
3
  • 2
    this post can help you with your problem 'str' does not support the buffer interface :) Commented Jan 12, 2016 at 17:14
  • 1
    make your unicode string a bytes object instead Commented Jan 12, 2016 at 17:15
  • use zlib.compress(sentence.encode('utf-8')) (if you like utf-8) Commented Jan 12, 2016 at 17:48

1 Answer 1

3

The error means that you are trying to pass str object (Unicode text) instead of binary data (byte sequence):

>>> import zlib
>>> zlib.compress('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Python 3.5 improves the error message here:

>>> import zlib
>>> zlib.compress('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

To save text as binary data, you could encode it using a character encoding. To compress the data, you could use gzip module:

import gzip
import io

with io.TextIOWrapper(gzip.open('sentence.txt.gz', 'wb'),
                      encoding='utf-8') as file:
    print(sentence, file=file)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.