python - 如何使用pysftp检查SFTP中是否存在文件?

标签 python sftp pysftp

我在 etl 中工作(第一次),我需要从客户端的 SFTP 中提取一些文件。我遇到的问题是文件号是可变的,所以我需要检查文件是否存在并获取它,文件格式类似于 "file_YYYY-MM-DD-number- n"其中 YYYY-MM-DD 是当前日期,n 是文件编号,所以如果有 7 个文件,我必须查找:

  • file_2019-08-25-number-1
  • file_2019-08-25-number-2

直到现在我发现我可以做这样的事情

cnopts = pysftp.CnOpts()
with pysftp.Connection(host=host, port=port, username=username, password=password, cnopts=cnopts) as sftp:
    files = sftp.listdir(directory)

我如何在文件中找到那里?

最佳答案

要使用 pysftp 检查文件是否存在,请使用 Connection.exists method :

with pysftp.Connection(...) as sftp:
    if sftp.exists("file_2019-08-25-number-1"):
        print("1 exists")
    if sftp.exists("file_2019-08-25-number-2"):
        print("2 exists")

虽然您最好一开始就不要使用 pysftp,因为它是一个死项目。请改用 Paramiko(参见 pysftp vs. Paramiko)。

要使用 Paramiko 检查文件是否存在,请使用 SFTPClient.stat .参见 How to check if the created file using Paramiko exec_command exists .


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

关于python - 如何使用pysftp检查SFTP中是否存在文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57648797/

相关文章:

python - SQLAlchemy 从两个具有空 LEFT JOIN 的表中选择返回空结果

python pygame如何合并循环?

javascript - python 的返回值在 javascript 中不可用

python - 在 Pandas 时间序列数据框中删除重复项

java - MessageChannel.send 方法什么时候返回?

sql - 应该如何使用数据仓库将数据提供给 Web 服务器?

Perl 使用 Net::SFTP::Foreign 摆脱服务器欢迎消息

python - 使用 Python 的 PySFTP 和 get_r - "No such file or directory"

python - 使用pysftp下载文件

python - 如何在Python中将Windows文件夹中的所有文件上传到SFTP文件夹