【发布时间】:2019-10-14 20:32:43
【问题描述】:
我正在尝试创建一个从内存中的 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
【问题讨论】: