1

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

Josh.h
  • 71
  • 1
  • 13

1 Answers1

2

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)
Be Chiller Too
  • 2,502
  • 2
  • 16
  • 42