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

时间:2019-10-14 20:32:43

标签: python ftp zip

我正在尝试创建一个函数,该函数从内存中的FTP下载文件并返回它。在这种情况下,我尝试下载一个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

1 个答案:

答案 0 :(得分:2)

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

您可以简单地为实例化的BytesIO对象分配变量以返回。更改:

with BytesIO() as download_file:

收件人:

download_file = BytesIO()

然后缩小该块。

相关问题