1

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

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Jimmy
  • 55
  • 1
  • 7

1 Answers1

0

Print the found file name, only if you actually find some:

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")
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992