Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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':
            ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading