我在 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/