Python search all files in subfolders containing specific subfolder name

Viewed 34

For example, I have 3 subfolders in the root directory and 2 subfolders in each subfolders, as shown below:

C:/main/canada/May 2022
C:/main/canada/Jun 2022
C:/main/usa/May 2022
C:/main/usa/Jun 2022
C:/main/mexico/May 2022
C:/main/mexico/Jun 2022

I am hoping to only scan for files in subfolders with name contains substring 'May'.

I am beginner and tried os, glob, pathlib, but don't think my thinking is correct.

1 Answers

You could try first globbing for subdirectories that match using glob.glob, and then finding their parents using pathlib.Path.parent:

import glob
import pathlib
for subdir in glob.glob("C:/main/*/*May*"):
    print(pathlib.Path(subdir).parent)
Related