尝试下载一个.gz文件,将其解压到内存中,然后逐行读取解压后的内容。你知道吗
import requests
r = requests.get(url)
print(r.headers)
with gzip.open(r.content, 'rb') as f:
'''Reading line by line'''
现在标题如下所示:
{'Date': 'Fri, 23 Aug 2019 07:19:28 GMT', 'Server': 'Apache', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'sameorigin', 'Referrer-Policy': 'no-referrer', 'X-Xss-Protection': '1', 'Last-Modified': 'Sat, 23 Jun 2018 09:21:46 GMT', 'ETag': '"8be6ca-56f4bad760d07"', 'Accept-Ranges': 'bytes', 'Content-Length': '9168586', 'X-Clacks-Overhead': 'GNU Terry Pratchett', 'Cache-Control': 'public, max-age=120', 'Keep-Alive': 'timeout=5, max=100', 'Connection': 'Keep-Alive', 'Content-Type': 'application/x-gzip'}
我得到的错误似乎是一个编码错误,但是我想请求已经在UTF-8中有了r.content
,并且gzip.open()
想要UTF-8,所以我没有得到这个错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
所以也有类似的问题,对我没有帮助。你知道吗
根据[Python-Requests.2]: Developer Interface - class requests.Response.content(强调是我的):
另一方面,[Python 3.Docs]: gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None):
要解决此问题,您不应该将
r.content
传递给gzip.open
,但是:用类似
io.BytesIO
的对象包装它,并将其传递给gzip.open
:把它传给
gzip.decompress
:或(与上一个项目符号组合)
将其保存到一个文件中,并将其名称传递给
gzip.open
(请注意,这非常慢,并且可能会引入其他潜在问题,如@Aran Fey所指出的):相关问题 更多 >
编程相关推荐