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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Have a look at the
zlib
-module of Python.Python 3:
zlib
-moduleA short example:
You can decompress the data again by:
Python 2:
zlib
-moduleA short example:
You can decompress the data again by:
As you can see, Python 3 uses bytearrays while Python 2 uses strings.
This should do. The zlib requires access to bytearray content, use buffer() for that.
In case the bytearray is not too large to be stored in memory more than once and known as
b
, you can just:If you need to do deocding first, have a look at the
decode()
method of the bytearray.The zlib module of Python Standard Library should meet your requirements :
This is the output under Python3.4, but it works same under Python 2.7 -