How to download only the latest file from SFTP server with Paramiko?

Use the SFTPClient.listdir_attr instead of the SFTPClient.listdir to get listing with attributes (including the file timestamp).

Then, find a file entry with the greatest .st_mtime attribute.

The code would be like:

latest = 0
latestfile = None

for fileattr in sftp.listdir_attr():
    if fileattr.filename.startswith('Temat') and fileattr.st_mtime > latest:
        latest = fileattr.st_mtime
        latestfile = fileattr.filename

if latestfile is not None:
    sftp.get(latestfile, latestfile)

For a more complex example, see How to get the latest folder that contains a specific file of interest in Linux and download that file using Paramiko in Python?

Leave a Comment