Alan H
Alan H

Reputation: 13

Python search all files in subfolders containing specific subfolder name

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.

Upvotes: 1

Views: 57

Answers (1)

pigrammer
pigrammer

Reputation: 3519

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)

Upvotes: 1

Related Questions