6

I am able to get a directory listing from Paramiko. And with listdir_attr I get the attributes. However, I need to sort this list by filename. If it returned a list of dictionaries I could use lambda to do the sort. But with it returning a list of SFTPAttributes I can't figure out how to do the sort other than creating a new list of dictionaries containing the data I care about and sorting that list. Before doing that is there a way to get a directory listing that is sorted by filename?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
efultz
  • 1,135
  • 2
  • 11
  • 26

1 Answers1

10

There's no way to make SFTPClient.listdir_attr return a sorted list.

Sorting is easy though:

files = sftp.listdir_attr()
files.sort(key = lambda f: f.filename)

Or for example, if you want to sort only files by size from the largest to the smallest:

from stat import S_ISDIR, S_ISREG
files = [f for f in files if not S_ISDIR(f.st_mode)]
files.sort(key = lambda f: f.st_size, reverse = True)
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992