Search code examples
pythonstringfilecompressionzlib

Python wont save compressed string using zlib


According to this website and guide it should be pretty trivial to save the string as compressed using zlib.

import zlib

my_data = 'Hello world'

compressed_data = zlib.compress(my_data, 2)

f = open('outfile.txt', 'w')
f.write(compressed_data)
f.close()

This code should save "Hello world" into txt file as compressed. I'm getting these errors:

compressed_data = zlib.compress(my_data, 2)

TypeError: a bytes-like object is required, not 'str'

I have also tried adding this but then i get other error saying

new_data = zlib.compress(my_data.encode())
compressed_data = zlib.compress(new_data, 2)

And then i get errors like this:

TypeError: write() argument must be str, not bytes

I have also tried adding b' in front of the text in my_data but that gave me new error

my_data = b'Hello world'

TypeError: write() argument must be str, not bytes


Solution

  • The example you found deep in the bowels of the interwebs is for Python 2, not Python 3. Python 3 makes a distinction between strings of characters and strings of bytes. All is well with the addition of two "b"s:

    import zlib
    my_data = b'Hello world'
    compressed_data = zlib.compress(my_data, 2)
    f = open('outfile.txt', 'wb')
    f.write(compressed_data)
    f.close()
    

    By the way, I have no idea why they wanted to use compression level 2. Just leave out the , 2. It will then use the default compression level, which is a good balance between time and compression ratio.