Search code examples
pythondirectorysubdirectory

how to find specific files in a directory with a pythonic code?


i am looking for specific files in a directory with many subdirectories

is there a pythonic way to rewrite this? I want to avoid the first for loop if possible:

mytypes = [".txt", ".doc", ".docx"]

for ext in mytypes:
    for filename in glob.iglob(directory+"/**/*/"+ext, recursive=True):
        print(filename)

thank you if you can point me to right direction. This works fine but I want to optimize the code because the list of mytypes might get bigger and the directory is heavy. This is what I tried but I believe there is a better way...


Solution

  • If you want to filter only some files, you will still need to have a mytypes variable.

    With that said you can use the pythonic way of avoiding for loops: list comprehensions.

    mytypes = [".txt", ".doc", ".docx"]
    
    files = [f for ext in mytypes for f in glob.glob(directory+"/**/*/"+ext)]
    
    print(files)