使用 Python Paramiko 从 SFTP 服务器读取 .csv 文件到内存 [英] Reading .csv file to memory from SFTP server using Python Paramiko
问题描述
我正在尝试在我的 Python 内存中读取 SFTP 上的 CSV 文件.我尝试了以下方法,它适用于 FTP 连接,但不适用于 SFTP.
I am trying to read a CSV file on the SFTP in my Python memory. I tried the following, which works fine for a FTP connection, but not for a SFTP.
例如,我想复制:
df = pd.read_csv(...)
但是没有先将它存储在本地(原因是因为我想将它作为 Cloud Function 运行,然后我不想在我的缓存中使用本地文件).
But without storing it first locally (reason being is because I want to run it as a Cloud Function and then I don't want local files in my cache).
我该如何做?
def read_file_sftp_local_memory(sftp, path, filename):
flo = BytesIO()
path_query = "".join(['RETR ', path, '/', filename])
sftp.retrbinary(path_query, flo.write)
flo.seek(0)
return flo
我也尝试了以下方法:
def read_file_csv(sftp, path, filename):
# Download
sftp.get("/".join( os.path.join(path, filename) ), filename)
# Read
df = pd.read_csv(filename)
# Delete
os.remove(filename)
# Return
return df
但这又回来了:
错误:
raise IOError(text)
OSError: Failure
推荐答案
假设您使用的是 Paramiko SFTP 库,请使用 SFTPClient.open
方法:
Assuming you are using Paramiko SFTP library, use SFTPClient.open
method:
f = sftp.open(path)
f.prefetch()
df = pd.read_csv(f)
f.close()
为了 prefetch
的目的,请参阅 读取使用 Python Paramiko SFTPClient.open 打开的文件方法很慢.
For the purpose of the prefetch
, see Reading file opened with Python Paramiko SFTPClient.open method is slow.
这篇关于使用 Python Paramiko 从 SFTP 服务器读取 .csv 文件到内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!