本文介紹了在 Python 中讀取 FTP 文件內容并同時用于 Pandas 和直接的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試從內存中的 FTP 服務器下載文件,將其轉換為數據幀,但也將其作為字節返回.代碼如下:
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')
在 Stack Overflow 上搜索后,建議只讀取 io 流:
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.
推薦答案
read_csv
可能會關閉文件".所以在調用 read_csv
之前請閱讀它:
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')
這篇關于在 Python 中讀取 FTP 文件內容并同時用于 Pandas 和直接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!