The main limitation that you’ve seen both with
.iterdir() before and then also with
.glob() is that it only matches in the directory that you’re directly in and none of the subdirectories. Now there’s another wildcard, the
** wildcard that allows you to do recursive matching, which means that it will apply the pattern both in the current directory as well as in any of the subdirectories.
So to make this a little more practical, take another look at the folder structure in here in the
notes/ directory—that was the main directory that we did any sort of searching in—you have these two
So there’s all of the
.txt files that are anywhere inside of the folder structure of the
notes/ directory. And you can do the same for Markdown files, for example. So I can say
notes_dir.glob(), and I want to get all the Markdown files, let’s say.
And this is going to give me both Markdown files that are somewhere in this folder structure. The first one is directly in the
notes/README.md—and the other one is nested deeper inside of
plans/monthly, and then it’s called
Markdown files inside of the folder structure. So these two do the same. You can either use the
**/ or you can use the recursive glob, the
.rglob() method, and then just pass in the normal pattern.
Now you’ve seen it with the
.txt files and also with the Markdown files, and you use it by putting
**/ at the beginning of your pattern, and then whatever else you want to match for the filename.
You can do recursive matching either using the
** wildcard, or you can also use the
.rglob() method that is equivalent to using
**/ inside of your pattern, but just a quicker way of doing the same thing.
04:02 And this wraps up the lessons about searching for files and folders inside of directories using wildcard characters and patterns. Now in the next lesson, you will learn about moving and deleting files and folders.
Become a Member to join the conversation.