使用 Python 在内存中下载和读取 ZIP 文件

问题:

你想通过在 Python 中从 URL 下载来获取 ZIP 文件,但你不想将其存储在临时文件中稍后提取,而是直接在内存中提取其内容。

解决方案

在 Python3 中可以使用 io.BytesIOzipfile(两者都存在于标准库中)在内存中读取它。 以下示例函数提供了一个基于生成器的现成方法来遍历 ZIP 中的文件:

download_extract_zip.py
import requests
import io
import zipfile

def download_extract_zip(url):
    """
    下载 ZIP 文件并在内存中提取其内容
    生成 (filename, file-like object) 对
    """
    response = requests.get(url)
    with zipfile.ZipFile(io.BytesIO(response.content)) as thezip:
        for zipinfo in thezip.infolist():
            with thezip.open(zipinfo) as thefile:
                yield zipinfo.filename, thefile

Check out similar posts by category: Allgemein