python - 我如何根据我提供的特定顺序进行排序

标签 python os.path ends-with

我正在尝试根据文件的扩展名对目录中的文件进行排序,但提供了我首先给出的顺序。假设我希望延期订单是

ext_list = [ .bb, .cc , .dd , aa ]

我能想到的唯一方法是遍历每个文件 并在每次遇到特定扩展时将它们放入列表中。

for subdir, dirs, files in os.walk(directory): 
     if file.endswith( '.bb') --> append file
     then go to the end of the directory
     then loop again
     if file.endswith( '.cc')  -->append file
     and so on...
return sorted_extension_list 

然后终于

        for file in sorted_extension_list :
            print file

最佳答案

还有另一种方法:

files = []

for _, _, f in os.walk('directory'):
    files.append(f)

sorted(files,key=lambda x: ext_list.index(*[os.path.basename(x).split('.',1)[-1]]))

['buzz.bb', 'foo.cc', 'fizz.aa']

编辑:我的输出没有 dd 因为我没有在我的本地测试目录中为它创建一个文件。无论如何它都会起作用。

关于python - 我如何根据我提供的特定顺序进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523328/

相关文章:

python - Python中如何获取文件的绝对路径?

python - 匹配字符串结尾

python - 类型错误 : endswith first arg must be str or a tuple of str, 不是 boolean 值

python - Scapy - 从三个接口(interface)中嗅探 2 个接口(interface)

python - 如何在 Django 模板中显示列表?

python - 在 python 中访问包含 matlab 类的 .mat 文件

python - 使用 Python 自底向上遍历目录树

python - TKinter 更新图片列表

java - 如何在 Java 中不使用内置方法 .endsWith() 实现 String.endsWith()

Python为矩阵的下三角生成掩码