I have binary data inside a bytearray that I would like to gzip first and then post via requests. I found out how to gzip a file but couldn't find it out for a bytearray. So, how can I gzip a bytearray via Python?
To compress an existing file to a gzip archive, read text in it and convert it to a bytearray. This bytearray object is then written to a gzip file. In the example below, 'zen. txt' file is assumed to be present in current directory.
To save a Pandas dataframe as gzip file, we use 'compression=”gzip”' in addition to the filename as argument to to_csv() function. In this example below, we save our dataframe as csv file without row index in compressed, i.e. gzip file, form. In addition to gzip file, we can also compress the file in other formats.
With the help of gzip. decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip. decompress(s) method. Return : Return decompressed string.
Have a look at the zlib
-module of Python.
Python 3: zlib
-module
A short example:
import zlib
compressed_data = zlib.compress(my_bytearray)
You can decompress the data again by:
decompressed_byte_data = zlib.decompress(compressed_data)
Python 2: zlib
-module
A short example:
import zlib
compressed_data = zlib.compress(my_string)
You can decompress the data again by:
decompressed_string = zlib.decompress(compressed_data)
As you can see, Python 3 uses bytearrays while Python 2 uses strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With