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

标签 python pandas postgresql sftp pysftp

我想读取安全 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 进行永久更改?

最佳答案

您已完成下载部分。

上传部分参见How to Transfer Pandas DataFrame to .csv on SFTP using Paramiko Library in Python? – 虽然是给Paramiko的,pysftp Connection.open method行为与 Paramiko SFTPClient.open 相同,所以代码是相同的(不过,你 should not use pysftp )。

完整代码可以是这样的:

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 Paramiko/pysftp "open" method is slow


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

关于python - 从 SFTP 文件读取 CSV/Excel 文件,使用 Pandas 对这些文件进行一些更改,然后保存回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61817226/

相关文章:

sql - Postgres JSON 数组带有连接?

java - Hibernate,按主键搜索返回表中的所有内容

python - 如何隐藏旧 Python 版本的不兼容代码?

python - 用字符串填充空列表元素python

python - Pandas:在 CSV 文件中使用整个字符串作为分隔符

python - 如何增加 pandas 系列中截断显示的行数

postgresql - 带限制的 Postgres 更新表

python - 判断一个矩阵是否为单位矩阵(numpy)

python - 加快 Pandas 应用或使用 map

python - Scapy 安装在 osx 上失败,并出现 dnet 导入错误