我正在尝试创建一个函数,该函数从内存中的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
通过将BytesIO
实例化为上下文管理器,它在退出时关闭了文件句柄,因此download_file
返回给调用者时不再具有打开的文件句柄。
您可以简单地为实例化的BytesIO
对象分配一个变量以代替返回。更改:
with BytesIO() as download_file:
至:
download_file = BytesIO()
并缩小块。