TypeError: 'str' does not support the buffer interface
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Question
00:31 Accepted answer (Score 298)
01:22 Answer 2 (Score 97)
01:53 Answer 3 (Score 43)
02:16 Answer 4 (Score 28)
02:38 Thank you
--
Full question
https://stackoverflow.com/questions/5471...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #gzip
#avk47
ACCEPTED ANSWER
Score 300
If you use Python3x then string is not the same type as for Python 2.x, you must cast it to bytes (encode it).
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'))
Also do not use variable names like string or file while those are names of module or function.
EDIT @Tom
Yes, non-ASCII text is also compressed/decompressed. I use Polish letters with UTF-8 encoding:
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)
ANSWER 2
Score 97
There is an easier solution to this problem.
You just need to add a t to the mode so it becomes wt. This causes Python to open the file as a text file and not binary. Then everything will just work.
The complete program becomes this:
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
outfile.write(plaintext)
ANSWER 3
Score 43
You can not serialize a Python 3 'string' to bytes without explict conversion to some encoding.
outfile.write(plaintext.encode('utf-8'))
is possibly what you want. Also this works for both python 2.x and 3.x.
ANSWER 4
Score 28
For Python 3.x you can convert your text to raw bytes through:
bytes("my data", "encoding")
For example:
bytes("attack at dawn", "utf-8")
The object returned will work with outfile.write.