pasztora
1/28/2019 - 2:46 PM

Finding part of a list element in a list (function)

# A function for creating a list of file paths in multiple subdirs
# FileKeys_any is a user defined list and is part of the filename that is listed by os.walk, see the examples below
# FileKeys_any = ["18_48", "18_49"]
# name = ["DM 18_48.xlsx", "DM 18_49.xlsx"]

def list_factory_files(dir, FileKeys_any):
    r = []
    for root, dirs, files in os.walk(dir):
        for name in files:
            if any(z in name for z in FileKeys_any): # Checking if any element of the FileKeys is present in the filename
                r.append(os.path.join(root, name)) # Creating a list of file names
    return r

# I like the version below more!!!!!!!!!
# An alternative to the previous with a for loop
# The output list is given in the order of the FileKeys, which could be very useful if the output will be sensitive to sorting.
# As otherwise it might happen that the output will be in a different order as the FileKeys.
def list_online_files(dir, FileKeys_OL):
    r = []
    for root, dirs, files in os.walk(dir):
        for key in FileKeys_OL:
            for name in files:
                if key in name: # Checking if any element of the FileKeys is present in the filename
                    r.append(os.path.join(root, name)) # Creating a list of file names
    return r