uniXVanXcel
uniXVanXcel

Reputation: 806

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

Upvotes: 3

Views: 679

Answers (4)

Brian
Brian

Reputation: 2242

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))

Upvotes: 3

gold_cy
gold_cy

Reputation: 14216

Here is another way of doing it:

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']

Edit: My output doesn't have dd since I didn't make a file for it in my local test dir. It will work regardless.

Upvotes: 5

Harvey
Harvey

Reputation: 5821

Using sorted with a custom key is probably best, but here's another method where you store the filenames in lists based on their extension. Then put those lists together based on your custom order.

def get_sorted_list_of_files(dirname, extensions):
    extension_map = collections.defaultdict(list)
    for _, _, files in os.walk(dirname):
        for filename in files:
            extension = os.path.splitext(filename)[1]
            extension_map[extension].append(filename)
    pprint.pprint(extension_map)
    sorted_list = []
    for extension in extensions:
        sorted_list.extend(extension_map[extension])
    pprint.pprint(extensions)
    pprint.pprint(sorted_list)
    return sorted_list

Upvotes: 1

Marco smdm
Marco smdm

Reputation: 1045

import os
# List you should get once:
file_list_name =['mickey.aa','mickey.dd','mickey_B.cc','mickey.bb']
ext_list = [ '.bb', '.cc' , '.dd' , '.aa' ]

order_list =[]
for ext in ext_list:
    for file in file_list_name:
        extension = os.path.splitext(file)[1]
        if extension == ext:
            order_list.append(file)

order_list is what you are looking for. Otherwise you can use the command sorted() with key attribute. Just look for it on SO!

Upvotes: 2

Related Questions