首页 > 解决方案 > 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

标签: pythonsftpparamiko

解决方案


打印找到的文件名,只有当你真的找到了一些:

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")

推荐阅读