Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...