With the next script, you can get the latest file from an SFTP folder specifying the folder path where the files are located, the prefix of the files, and the files extension.

First of all, we are going to use the library Paramiko to establish an ssh connection to the SFTP server using the class SFTPClient. To do this the first step is to include the library and the configuration parameters.

Paramiko web page https://www.paramiko.org

Paramiko installation guide https://www.paramiko.org/installing.html

import paramiko
import re
hostname = '<sftp-host>' 
portnumber = <sftp-port-number>
username = '<sftp-username>'
password = '<sftp-password>'
filepath = '<sftp-file-path-location>' #example: /files/
fileprefix = '<file-prefix>' #example: Documents_
fileextension = '<file-extension>' #example: csv|CSV

After that, you need to create the connection to the SFTP server and open the remote folder that contains the files.

try:
    transport = paramiko.Transport((hostname,portnumber))
    transport.connect(None,username,password)
    sftp = paramiko.SFTPClient.from_transport(transport)
except:
    print('Invalid credentials')
    

try:
    sftp.chdir(filepath)
except:
    print('Invalid folder')

Finally, we need to use a FOR to loop through all the files in the folder, then we are going to use an IF statement to validate each file that matches with the prefix and the extension passed as parameters using a regular expression.

#variable declarations
latest_file_date = 0
latestfile = None

#get the last file from the folder with the prefix file name
for fileattr in sftp.listdir_attr():    
    if re.search(f"^{fileattr.filename}.*({fileextension})", fileattr.filename) and fileattr.st_mtime > latest_file_date:
        latest_file_date = fileattr.st_mtime
        latestfile = fileattr.filename
        

if latestfile is not None:
    print(latestfile)

Tagged in:

, ,