【问题标题】:Unzip downloaded gzipped content on the fly即时解压缩下载的 gzip 压缩内容
【发布时间】:2023-05-10 15:38:04
【问题描述】:

我正在使用 python 下载一个 gzip 压缩的 CSV,我想将它作为 csv 直接写入磁盘。

我尝试了以下几种变体:

url ='blabla.s3....csv.gz'
filename = 'my.csv'

compressed = requests.get(url).content
data = gzip.GzipFile(fileobj=compressed)
with open(filename, 'wb') as out_file:
    out_file.write(data)

但是我遇到了各种错误 - 我不确定我是否将响应的正确部分传递给 gzip 方法。如果有人有这方面的经验,我们将不胜感激。

【问题讨论】:

    标签: python python-3.x python-requests gzip


    【解决方案1】:

    您应该可以使用zlib 来解压缩响应。

    import zlib
    
    res = requests.get(url)
    data = zlib.decompress(res.content, zlib.MAX_WBITS|32)
    

    现在,写入文件:

    with open(filename, 'wb') as f:
        f.write(data)
    

    【讨论】:

      最近更新 更多