Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gzip a bytearray in Python?

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?

like image 955
Canol Gökel Avatar asked Nov 05 '14 09:11

Canol Gökel


People also ask

How do I gzip in 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.

How do I compress a csv file to gzip in Python?

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.

How do you compress and decompress a string in Python?

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.


1 Answers

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.

like image 74
mozzbozz Avatar answered Sep 27 '22 18:09

mozzbozz