python - how to inflate gzipped, base64d string

*爱你&永不变心* 提交于 2020-03-18 09:02:19

问题


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 GzipFilein 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!