본문 바로가기
파이썬

파이썬 TypeError : 'str'은 버퍼 인터페이스를 지원하지 않습니다.

by º기록 2020. 10. 7.
반응형
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(plaintext) 

위의 파이썬 코드는 다음과 같은 오류를 발생시킵니다.

Traceback (most recent call last):
  File "C:/Users/Ankur Gupta/Desktop/Python_works/gzip_work1.py", line 33, in <module>
    compress_string()
  File "C:/Users/Ankur Gupta/Desktop/Python_works/gzip_work1.py", line 15, in compress_string
    outfile.write(plaintext)
  File "C:\Python32\lib\gzip.py", line 312, in write
    self.crc = zlib.crc32(data, self.crc) & 0xffffffff
TypeError: 'str' does not support the buffer interface

 

해결 방법

 

Python3x를 사용하는 경우 string 은 Python 2.x와 동일한 유형이 아니므로이를 바이트로 캐스트 (인코딩)해야합니다.

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

또한 string 또는 file 과 같은 변수 이름은 모듈 또는 함수의 이름 인 동안 사용하지 마십시오.

@Tom 수정

예, 비 ASCII 텍스트도 압축 / 압축 해제됩니다. UTF-8 인코딩으로 폴란드어 문자를 사용합니다.

plaintext = 'Polish text: acelnószzACELNÓSZZ'
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)

 

참조 페이지 https://stackoverflow.com/questions/5471158

 

 

반응형

댓글