我具有以下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
对于为文件可用性/下载成功实施或不成功实施适当的错误处理提供的任何帮助,我们深表感谢。预先感谢
答案 0 :(得分:0)
仅在实际找到文件名时才打印找到的文件名:
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")