Paramiko 得到排序的目录列表 [英] Paramiko get sorted directory listing
问题描述
我可以从 Paramiko 获得目录列表.使用 listdir_attr
我得到属性.但是,我需要按文件名对这个列表进行排序.如果它返回一个字典列表,我可以使用 lambda 来进行排序.但是随着它返回一个 SFTPAttributes
列表,除了创建一个包含我关心的数据的新字典列表并对该列表进行排序之外,我无法弄清楚如何进行排序.在此之前,有没有办法获得按文件名排序的目录列表?
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?
推荐答案
没有办法让 SFTPClient.listdir_attr
返回一个排序列表.
There's no way to make SFTPClient.listdir_attr
return a sorted list.
排序很容易:
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)
这篇关于Paramiko 得到排序的目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!