Using the Star Wildcard
So if I head back over to IDLE, and I’m again inside of this notes directory—well, let’s take a moment and remember what it looks like. So inside of the
notes/ directory, you have a couple of folders,
yearly/, and then you have also have three files, a
README.md file and two files, one called
goals1.txt and one called
Now I want to filter out for only
.txt files that are directly in the
notes/ directory. So I want to get as a result
goals2.txt, but none of the folders and also not the Markdown file.
And then both of these files end with
.txt, so they’re a match with this pattern. Now, you can use the
* character also more than once in a pattern. For that, let’s move to a different directory.
We’re going to look inside of
yearly/, and I want to match the files that start with the
2 and then end with a
3. So I only want to match this one file,
2033, but I’m going to build a pattern using the
And then just to confirm … All right, this is the correct path. And then in here I can say
yearly_dir.glob(). And now I can build the pattern and I said it should start with a
2, then could have any characters, and then it should end with a
And then again, it could have any character. So I don’t care which file extension it has. I’ve got to close the string as well. And then, again, wrap it inside of a call to
list(), just so we can see the output.
And this now only gives me
2033 because now it’s matching this specific
3 character followed by a dot. And the file that matched before that has a
4 here before the
. doesn’t fit to this pattern anymore. So as you can see, you can use the
* more than once in a pattern, and it just matches any number of any characters.
03:38 What happens if nothing matches the search pattern that you’re using? Try that out as well. So if I use the same pattern, but let’s say I want it to start—oops, accidental Enter press. Let me try that again.
Also, it’s important to remember that the pattern only applies to the actual filename, so it does not apply to the whole path. This is just a representation of the
Path object. So if I was to look for,
let’s say anything, and then it ends with
ly. So I’m trying to address this
yearly here, right? But it’s not the filename. So this is not going to match anything because the search only goes on the filenames, so on the last part of the path, which means the actual files and folders that are inside of the directory that I am calling the
.glob() method on, which in this case is the
Become a Member to join the conversation.