我正在尝试从内存中的 FTP 服务器下载文件,将其转换为数据帧,但也将其作为字节返回。代码如下:
import io
import pandas as pd
from ftplib import FTP
ftp_connection.cwd(ftp_folder)
download_file = io.BytesIO()
ftp_connection.retrbinary('RETR ' + str(file_name), download_file.write)
download_file.seek(0)
file_to_process = pd.read_csv(download_file, engine='python')
在 Stack Overflow 上搜索后,建议只读取 io 流:
download_file.read()
ValueError: I/O operation on closed file.
不确定接下来要尝试什么,而不是将文件写入某处并再次以字节形式读取它。
请您参考如下方法:
read_csv 可能会关闭"file"。所以在调用 read_csv 之前阅读它:
download_file.seek(0)
contents = download_file.read()
download_file.seek(0)
file_to_process = pd.read_csv(download_file, engine='python')
