How can I create a GzipFile instance from the “file-like object” that urllib.urlopen() returns?

后端 未结 3 2029
悲&欢浪女
悲&欢浪女 2020-12-31 06:10

I’m playing around with the Stack Overflow API using Python. I’m trying to decode the gzipped responses that the API gives.

import urllib, gzip

url = urllib         


        
3条回答
  •  有刺的猬
    2020-12-31 06:59

    import urllib2
    import json
    import gzip
    import io
    
    url='http://api.stackoverflow.com/1.0/badges/name'
    page=urllib2.urlopen(url)
    gzip_filehandle=gzip.GzipFile(fileobj=io.BytesIO(page.read()))
    json_data=json.loads(gzip_filehandle.read())
    print(json_data)
    

    io.BytesIO is for Python2.6+. For older versions of Python, you could use cStringIO.StringIO.

提交回复
热议问题