Search code examples
pythondirectorypathglobsubdirectory

How to access a folder with a specific name by iterating through various subdirectories - Python?


I would like to access the "PNG FILES" folder that are randomly located in various different subdirectories of my 'All images' folder. I have tried the following:

import glob

path = r"C:\main folder\All images"
for f in glob.iglob((path) + 'PNG FILES', recursive=True):
    print (f)

However, this does not give me an output. I know you can easily locate files with a certain extension using glob.iglob but I'm having trouble locating folders with a specific name ('PNG FILES' in this case). Any help on this would be appreciated!


Solution

  • You can use this method: https://docs.python.org/3/library/os.html#os.walk and then check the folder names in the loop.

    for root, dirs, files in os.walk(path):
        for name in dirs:
            if name == 'PNG FILES':
                ...