问题
I'm just wondering how is it possible to inflate/decompress a string of text that is a gzipped compressed string that also hase base64 encoding?
For instance, all the python examples seem to focus on opening a file, whereas I want to work on a gzipped string.
回答1:
You can use base64 and zlib libraries:
import base64, zlib
decoded_data = zlib.decompress(base64.b64decode(encoded_data))
The gzip module is only for file operations: https://docs.python.org/2/library/gzip.html. It uses zlib for actual compression/decompression.
回答2:
Under python3, other answers didn't help me but I found this:
import base64
import zlib
data = 'H4sIAAAAAAAAAHWPwQqCQBCGX0Xm7EFtK+smZBEUgXoLCdMhFtKV3akI8d0bLYmibvPPN3wz00CJxmQnTO41whwWQRIctmEcB6sQbFC3CjW3XW8kxpOpP+OC22d1Wml1qZkQGtoMsScxaczKN3plG8zlaHIta5KqWsozoTYw3/djzwhpLwivWFGHGpAFe7DL68JlBUk+l7KSN7tCOEJ4M3/qOI49vMHj+zCKdlFqLaU2ZHV2a4Ct/an0/ivdX8oYc1UVX860fQDQiMdxRQEAAA=='
json_str = zlib.decompress(base64.b64decode(data), 16 + zlib.MAX_WBITS).decode('utf-8')
hope this helps
回答3:
The GzipFile
in the gzip
module allows you to provide a fileobj
argument. If the string is really gzipped (ie: it has the proper headers) you can then wrap the string in a StringIO
object and pass it around
import base64
import gzip
from io import StringIO
gzippedstr = fetchgzippedstr() # wherever it may come from
gzcontent = gzip.GzipFile(fileobj=StringIO(gzippedstr))
b64content = gzcontent.read()
content = base64.b64decode(b64content)
来源:https://stackoverflow.com/questions/37022199/python-how-to-inflate-gzipped-base64d-string