我正在尝试从内存中的 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')
关于python - 用Python读取FTP文件内容并同时用于Pandas和直接使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58320638/