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