2016-01-12 38 views
0

我不斷收到這個錯誤「TypeError:'str'不支持緩衝區接口」不知道發生了什麼問題。任何援助將是偉大的。任何想法如何解決TypeError:'str'不支持緩衝區接口?

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) 
+2

這篇文章可以幫助你解決問題[「STR」不支持緩衝區接口(http://stackoverflow.com/questions/26945613/str -does-not-support-the-buffer-interface-python3-from-python2):) –

+1

謝謝,我來看看! – Trent

+1

使用'zlib.compress(sentence.encode('utf-8'))'(如果你喜歡utf-8)使你的unicode字符串成爲字節對象而不是 –

回答

3

的錯誤意味着你正在嘗試,而不是二進制數據(字節序列)通過str對象(Unicode文本):

>>> 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提高這裏的錯誤消息:

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

要將文本保存爲二進制數據,可以使用字符編碼對其進行編碼。對數據進行壓縮,可以使用gzip模塊:

import gzip 
import io 

with io.TextIOWrapper(gzip.open('sentence.txt.gz', 'wb'), 
         encoding='utf-8') as file: 
    print(sentence, file=file) 
相關問題