efultz
efultz

Reputation: 1265

Paramiko get sorted directory listing

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?

Upvotes: 6

Views: 2787

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202272

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)

Upvotes: 10

Related Questions