Search code examples
pythonos.pathends-with

How can I sort given a specific order that I provide


I am trying to sort files in a directory given their extension, but provided an order that I give first. Let's say I want the extension order to be

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

The only way that I can think of would be to go through every single file and place them in a list every time a specific extension is encountered.

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 

and then finally

        for file in sorted_extension_list :
            print file

Solution

  • You can use sorted() with a custom key:

    import os
    
    my_custom_keymap = {".aa":2, ".bb":3, ".cc":0, ".dd":1}
    def mycompare(f):
        return my_custom_keymap[os.path.splitext(f)[1]]
    
    files = ["alfred.bb", "butters.dd", "charlie.cc", "derkins.aa"]
    
    print(sorted(files, key=mycompare))
    

    The above uses the mycompare function as a custom key compare. In this case, it extracts the extension, and the looks up the extension in the my_custom_keymap dictionary.

    A very similar way (but closer to your example) could use a list as the map:

    import os
    
    my_custom_keymap = [".cc", ".dd", ".aa", ".bb"]
    def mycompare(f):
        return my_custom_keymap.index(os.path.splitext(f)[1])
    
    files = ["alfred.bb", "butters.dd", "charlie.cc", "derkins.aa"]
    
    print(sorted(files, key=mycompare))