读取Python中的FTP个文件内容,同时对Pandas直接使用

Read FTP file contents in Python and use it at the same time for Pandas and directly

我正在尝试从内存中的 FTP 服务器下载文件,将其转换为数据帧,但也 return 将其转换为字节。代码如下:

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')

我认为使用 tentaclio 包更容易:

with tentaclio.open("ftp://user:password@host/path/name_file.csv") as reader:
    df = pd.read_csv(reader)