我正在使用请求库和 python 2.7 从 web api 下载 gzip 文本文件。使用下面的代码,我能够成功发送一个 get 请求,并从标头判断,以 gzip 文件的形式接收响应。
我知道如果请求从头中检测到响应被 gzip 压缩,它会自动为您解压缩这些文件。我想以文件流的形式进行下载,并将内容写入磁盘以供存储和未来分析。
当我在我的工作目录中打开结果文件时,我得到这样的字符:—}}¶— Q@Ï 'õ
作为参考,一些响应头包括 'Content-Encoding': 'gzip', 'Content-Type': 'application/download', 'Accept-Encoding,User-Agent'
我用二进制写错了吗?我是否没有正确编码文本(即它可能是 ASCII 还是 utf-8)?响应标头中没有注明明显的字符编码。
try:
response = requests.get(url, paramDict, stream=True)
except Exception as e:
print(e)
with open(outName, 'wb') as out_file:
for chunk in response.iter_content(chunk_size=1024):
out_file.write(chunk)
Run Code Online (Sandbox Code Playgroud)
编辑 3.30.2016:现在我稍微改变了我的代码以利用 gzipstream 库。我尝试使用流读取响应内容中的整个 Gzipped 文本文件:
with open(outName, 'wb') as out_file, GzipStreamFile(response.content) as fileStream:
streamContent = fileStream.read()
out_file.write(streamContent)
Run Code Online (Sandbox Code Playgroud)
然后我收到了这个错误:out_file.write(streamContent) AttributeError: '_GzipStreamFile' object has no attribute 'close'
输出是一个空文本文件,文件名符合预期。我是否需要在with块外初始化我的 …