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

后端 未结 3 2054
悲&欢浪女
悲&欢浪女 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:58

    Here is a new update for @stefanw's answer, to whom that might think it too expensive to use that much memory.

    Thanks to this article(https://www.enricozini.org/blog/2011/cazzeggio/python-gzip/, it explains why gzip doesn't work), the solution is to use Python3.

    import urllib.request
    import gzip
    
    response = urllib.request.urlopen('http://api.stackoverflow.com/1.0/badges/name')
    with gzip.GzipFile(fileobj=response) as f:
        for line in f:
            print(line)
    

提交回复
热议问题