Search code examples
pythonpriority-queue

Transformation of file list based on higher priority


I have a list of files in a directory with different names, I need to transform all the files one at a time based on priority.Files starting with 'AB' to have higher priority over the ones with 'CD'. Within each of those set order the file by Name ascending and pick the first one.

Input :
AB_2908_02P.xml
CD_2908_02P.xml

Code:

def Send_Request(self):
    Directory = "c://users/request/"
    #Type = 'AB','CD'
    xml_files = Type + '_' + '2908_02P' + '.xml'
    if os.path.exists(Directory+xml_files):
        for file in os.listdir(Directory):
            #AB_2908_02P.xml
            #CD_2908_02P.xml
            if file.startswith('AB'):
                print ("first priority")
            elif file.startswith('CD'):
                print("second priority")
                

Can anyone please let me know what is the best way to use a priority queue?


Solution

  • you could take advantage of python's native capability to sort tuples. create a lookup table prio for your prefixes, then sort the list of files using a sort key: the function generates a tuple (prio, filename) for each file as sorting criteria:

    import math
    
    files = [
        "AB_2908_02P.xml",
        "CD_2908_02P.xml",
        "AB_2909_02P.xml",
        "CD_2910_02P.xml",
        "XY_2908_03P.xml",
        "CD_3008_02P.xml",
        "AC_xxxx_yyy_zzzzz.xml"
    ]
    
    prio = {
        'AB': 5,
        'CD': 0,
        'XY': 3
    }
    
    for filename in sorted(files, key=lambda f: (prio.get(f.partition('_')[0], math.inf), f)):
        print(filename)
    

    prints:

    CD_2908_02P.xml
    CD_2910_02P.xml
    CD_3008_02P.xml
    XY_2908_03P.xml
    AB_2908_02P.xml
    AB_2909_02P.xml
    AC_xxxx_yyy_zzzzz.xml
    

    NOTE: the code uses math.inf as default priority in case no prio is defined for a certain prefix (as is the case with AC in the example above).