我正在尝试创建一个从内存中的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发布于 2019-10-15 04:41:44
通过将BytesIO实例化为上下文管理器,它在退出时关闭文件句柄,因此download_file在返回给调用者时不再具有打开的文件句柄。
您只需为实例化的BytesIO对象分配一个返回变量即可。更改:
with BytesIO() as download_file:至:
download_file = BytesIO()然后把积木压下来。
https://stackoverflow.com/questions/58383707
复制相似问题