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

2024-04-23 14:38:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在安全的SFTP文件夹中读取一些CSV/Excel文件,对这些文件进行一些更改(每个文件中的固定更改,如删除第2列),将它们上载到Postgre DB,并将它们上载到Python中不同的SFTP路径

最好的方法是什么

我已使用PySTFP库连接到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)

我应该如何继续上传到DB并将这些更改永久保存到CSV


Tags: 文件csvimportdbasconnectionexcelpd
2条回答

您已经完成了下载部分

对于上传部分,请参见How to Transfer Pandas DataFrame to .csv on SFTP using Paramiko Library in Python?–对于Paramiko,pysftp ^{} method的行为与Paramiko ^{}相同,因此代码是相同的

完整代码可以如下所示:

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

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

我建议采用这种方法:

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

相关问题 更多 >