4

I have this code that pulls files from a server using Paramiko. How can I get these files sorted by modification date?

ssh = paramiko.SSHClient()
# automatically add keys without requiring human intervention
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )

ssh.connect(sftpURL, username=sftpUser, password=sftpPass)

sftp = ssh.open_sftp()
filesInSFTP = sftp.listdir(sftpPullDirectory)
# Get only the XML and XLSX files
filesInSFTP = [file for file in filesInSFTP if file.lower().endswith(('.xml', '.xlsx'))]
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
mastercool
  • 463
  • 12
  • 35

1 Answers1

5

Retrieve the listing with file attributes (including the modification time) using SFTPClient.listdir_attr. And then sort the list by SFTPAttributes.st_mtime field.

filesInSFTP = sftp.listdir_attr(sftpPullDirectory)
filesInSFTP.sort(key = lambda f: f.st_mtime)

Related questions:


Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992