我有下面的 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/