从 SFTP 文件中读取 CSV/Excel 个文件,使用 Pandas 对这些文件进行一些更改,然后保存

Read CSV/Excel files from SFTP file, make some changes in those files using Pandas, and save back

我想读取安全 SFTP 文件夹中的一些 CSV/Excel 文件,在这些文件中进行一些更改(每个文件中的固定更改,如删除第 2 列),将它们上传到 Postgre 数据库,然后上传他们到 Python

中的不同 SFTP 路径

最好的方法是什么?

我已经使用 pysftp 库连接到 SFTP 并且正在阅读 Excel:

import pysftp
import pandas as pd

myHostname = "*****"
myUsername = "****"
myPassword = "***8"
cnopts =pysftp.CnOpts()
cnopts.hostkeys = None  

sftp=pysftp.Connection(host=myHostname, username=myUsername, 
password=myPassword,cnopts=cnopts)
print ("Connection succesfully stablished ... ")
sftp.chdir('test/test')
#sftp.pwd
a=[]
for i in sftp.listdir_attr():
    with sftp.open(i.filename) as f:
        df=pd.read_csv(f)

我应该如何继续上传到数据库并使 CSV 的这些更改永久化?

这是一个问题中的几个问题:)

我建议采用这种方法:

  1. 制作文件的本地副本(不确定它有多大,没有必要在本地计算机和 sftp 服务器之间来回移动它。您可以使用 get 方法
  2. 使用 pandas 对您的数据进行操作,然后使用 to_csv 方法将其转储回 csv
  3. 使用 pandas.io 或纯 SQLAlchemy 将数据加载到 postgree。检查文档 here
  4. 使用put方法将文件上传到您想要的目的地

您已完成下载部分。

上传部分见How to Transfer Pandas DataFrame to .csv on SFTP using Paramiko Library in Python? – While it's for Paramiko, pysftp Connection.open method behaves identically to Paramiko SFTPClient.open,所以代码相同

完整代码如下:

with sftp.open("/remote/path/data.csv", "r+", bufsize=32768) as f:
    # Download CSV contents from SFTP to memory
    df = pd.read_csv(f)

    # Modify as you need (just an example)
    df.at[0, 'Name'] = 'changed'

    # Upload the in-memory data back to SFTP
    f.seek(0)
    df.to_csv(f, index=False)
    # Truncate the remote file in case the new version of the contents is smaller
    f.truncate(f.tell())

以上更新同一个文件。如果你想上传到不同的文件,使用这个:

# Download CSV contents from SFTP to memory
with sftp.open("/remote/path/source.csv", "r") as f:
    df = pd.read_csv(f)

# Modify as you need (just an example)
df.at[0, 'Name'] = 'changed'

# Upload the in-memory data back to SFTP
with sftp.open("/remote/path/target.csv", "w", bufsize=32768) as f:
    df.to_csv(f, index=False)

为了bufsize的目的,见:
Writing to a file on SFTP server opened using pysftp "open" method is slow


强制警告:不要设置cnopts.hostkeys = None,除非你不关心安全。有关正确的解决方案,请参阅 Verify host key with pysftp