TypeError: 'str' does not support the buffer interface

后端 未结 7 958
南方客
南方客 2020-11-22 03:11
plaintext = input(\"Please enter the text you want to compress\")
filename = input(\"Please enter the desired filename\")
         


        
7条回答
  •  庸人自扰
    2020-11-22 03:56

    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)
    

提交回复
热议问题