mastercool
mastercool

Reputation: 523

How to sort file list pulled from SFTP server using Paramiko by modification date?

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'))]

Upvotes: 4

Views: 2321

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202168

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

Upvotes: 7

Related Questions