python - 如何使用 Python paramiko sftp 在获取具有最新时间戳的文件名时添加错误处理

标签 python sftp paramiko

我有下面的 Python Paramiko SFTP 脚本来从 SFTP 下载文件,其中包含部分文件名,并且文件上传具有最新的时间戳(基于 How to download only the latest file from SFTP server with Paramiko? )。但是我不确定如何向代码添加错误处理:

RemotePath='/WM_Universe/out/'
RemoteFilename='EDI_CAB_Red_Part_'
LocalPath='O:/Datafeed/Debt/WMDaten/PoolFactor/In/'

#Create Date LongDate/ShortDate
date = datetime.date.today() 

ldate=(date.strftime ("%Y%m%d"))

latest = 0
latestfile = None

for fileattr in sftp.listdir_attr():

if fileattr.filename.startswith(RemoteFilename + ldate) and fileattr.st_mtime > latest:
    latest = fileattr.st_mtime
    latestfile = fileattr.filename

print (LocalPath + latestfile)

if latestfile is not None:
    sftp.get(latestfile, LocalPath + latestfile)  

如果该文件不可用,具有上述名称且具有最新时间戳,我会收到以下错误:

Traceback (most recent call last):
  File "C:/Users/username/PycharmProjects/SFTP.py", line 72, in <module>
    print (LocalPath + latestfile)
TypeError: can only concatenate str (not "NoneType") to str

非常感谢您为文件可用性/下载成功与否实现适当的错误处理提供的帮助。提前致谢

最佳答案

打印找到的文件名,仅当您确实找到了一些文件时:

if fileattr.filename.startswith(RemoteFilename + ldate) and fileattr.st_mtime > latest:
    latest = fileattr.st_mtime
    latestfile = fileattr.filename

if latestfile is not None:
    print (LocalPath + latestfile)
    sftp.get(latestfile, LocalPath + latestfile)  
else:
    print("No such file")

关于python - 如何使用 Python paramiko sftp 在获取具有最新时间戳的文件名时添加错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53285076/

相关文章:

linux - 如何在远程本地网络计算机上编辑文件,但不能在 Internet 上编辑文件 :

python - 如果进程通过 paramiko ssh session 运行并且最后以 "&"运行,则进程终止

python - 是否有必要在多线程的 Paramiko 中为每个线程打开一个 SFTPClient?

python - 如何查询Python事件循环单调时钟分辨率

python - 当一条线上有多个停止点时,python何时在一条线上停止?

linux - 如何通过现有的 SSH 连接使用 OSX Coda 到 SFTP?

batch-file - Windows CMD 行 'sftp' 使用密码进行身份验证

python - 我发现书中有错误 "Grokking Algorithms"

python - 如何在python中将负整数值转换为十六进制

python - Paramiko SFTP 客户端在抛出 IOError 后创建零大小的文件