Python FTP:从 FTP 读取 .xlsx 作为 pandas 数据帧,而不将 .xlsx 写入磁盘

Python FTP: Read .xlsx as pandas dataframe from FTP without writting .xlsx to disk

我想从 FTP 连接读取 .xlsx 文件作为 pandas 数据帧,但是我想在内存上执行此操作而不将 .xlsx 写入本地磁盘。

这是我当前的代码:

filename = 'my_excel.xlsx'
localfile = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
ftp.quit()
localfile.close()

在本节之后,我可以从本地磁盘读取 .xlsx 作为 pandas 数据帧,但是我想在缓冲存储器中处理它。

我该怎么做。感谢您的帮助=)

你可以使用一个io.BytesIO对象来写入数据流,然后读入pandas。

import pandas as pd
from io import BytesIO

excel_fp = BytesIO()
filename = 'my_excel.xlsx'
ftp.retrbinary('RETR ' + filename, excel_fp.write, 1024)

# reset the cursor to the start of the file stream
excel_fp.seek(0)
df = pd.read_excel(excel_fp)