python - How to add error handling with Python paramiko sftp on get filename with latest timestamp
问题描述
I have the below Python Paramiko SFTP script to download a file from SFTP where part of the filename is included and where file upload has the most recent timestamp (based on How to download only the latest file from SFTP server with Paramiko?). However I am not sure how to go about adding error handling to the code:
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)
If the file is not available with the above name and having the most recent timestamp I get the following error:
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
I appreciate any help on implementing appropriate error handling for file availability/download successful or not. Thanks in advance
解决方案
打印找到的文件名,只有当你真的找到了一些:
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")
推荐阅读
- ios - 如何从侧面菜单视图控制器移回标签栏视图控制器?
- angular - 如何正确处理和控制 Angular 和 Web API 中的错误 - 2
- c - 在链表交换期间未传递指针
- image-processing - libvips 旋转在设备上没有剩余空间
- javascript - Javascript 分面搜索
- reactjs - React:从父组件通过 NavLink 访问 props 数据
- php - 将数据库中的数据与 php 变量进行比较
- testing - TestNG 6.10+ 优先级比保留顺序更重要
- javascript - 如何从 PouchDB 函数中获取变量到 JS 变量
- ios - 在 iOS 设备关闭时获取通知?