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

試著忘記壹切 提交于 2020-05-08 16:07:53

问题


I am trying to download a file from an FTP server in memory, transform it to a dataframe but also return it as bytes. Code as follows:

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

After searching on Stack Overflow, the suggestion was to just read the io stream:

download_file.read()
ValueError: I/O operation on closed file.

Not sure what to try next, without writing the file somewhere and reading it again as bytes.


回答1:


read_csv probably closes the "file". So read it before you call read_csv:

download_file.seek(0)
contents = download_file.read()
download_file.seek(0)
file_to_process = pd.read_csv(download_file, engine='python')


来源:https://stackoverflow.com/questions/58320638/read-ftp-file-contents-in-python-and-use-it-at-the-same-time-for-pandas-and-dire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!