uni*_*cel 3 python ends-with os.path
我试图在给定扩展名的目录中对文件进行排序,但提供了我先给出的订单.假设我想要扩展订单
ext_list = [ .bb, .cc , .dd , aa ]
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是遍历每个文件,并在每次遇到特定扩展时将它们放在列表中.
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
Run Code Online (Sandbox Code Playgroud)
然后最后
for file in sorted_extension_list :
print file
Run Code Online (Sandbox Code Playgroud)
这是另一种方法:
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']
Run Code Online (Sandbox Code Playgroud)
编辑:我的输出没有,dd
因为我没有在我的本地测试目录中为它创建一个文件.无论如何都会奏效.