从内存中的 FTP 下载 Zip 文件并解压缩

Download Zip File From FTP in Memory and Unzip it

我正在尝试创建一个函数,从内存中的 FTP 下载一个文件,然后 returns 它。在这种情况下,我尝试下载一个 zip 文件并在不在本地写入文件的情况下将其解压缩,但出现以下错误:

ValueError: I/O operation on closed file.

这是我当前的代码:

from io import BytesIO
from ftplib import FTP_TLS

def download_from_ftp(fp):
    """
    Retrieves file from a ftp
    """
    ftp_host = 'some ftp url'
    ftp_user = 'ftp username'
    ftp_pass = 'ftp password'

    with FTP_TLS(ftp_host) as ftp:
        ftp.login(user=ftp_user, passwd=ftp_pass)
        ftp.prot_p()
        with BytesIO() as download_file:
            ftp.retrbinary('RETR ' + fp, download_file.write)
            download_file.seek(0)
            return download_file

这是我尝试解压缩文件的代码:

import zipfile
from ftp import download_from_ftp

ftp_file = download_from_ftp('ftp zip file path')
with zipfile.ZipFile(ftp_file, 'r') as zip_ref:
    # do some stuff with files in the zip

通过将 BytesIO 实例化为上下文管理器,它会在退出时关闭文件句柄,因此 download_file 在 returned 给调用者时不再有打开的文件句柄.

您可以简单地为 return 实例化的 BytesIO 对象分配一个变量。变化:

with BytesIO() as download_file:

至:

download_file = BytesIO()

并缩进块。