Listing Conditionally Using .rglob()
00:00
In this lesson, you’ll learn conditional listing using .rglob()
. Just the same as with the .glob()
method, you can adjust the glob pattern of .rglob()
to give you only a certain file extension, except that the .rglob()
method will always search recursively. To see how .rglob()
differs from .glob()
try it out now. So type list(desktop
00:32
and then close off your list constructor with the remaining parentheses. By adding the md
to the glob
pattern, .rglob()
produces only md
files across different directories and subdirectories.
00:46
Hit Enter. And a list filled with the items that end in md
file extension is returned. You might see hash-tables, iterate-dict, and tictactoe.
00:59
How about you try listing all the items that start with the character ‘R’? Type list(desktop
01:07
.rglob("r")
lowercase, and then a single asterisk, and then close off your list constructor and hit Enter. For this example, you may see realpython, but you’ll also see rename_files.py and request.py.
01:26
This is due to .rglob()
searching recursively, so that items in the subdirectory scripts were also found. You can actually use .glob()
and get it to behave in the same way as .rglob()
by adjusting the glob pattern passed as an argument.
01:42
To try this out, type list (desktop
01:49
`.glob(“) and then two asterisks followed by a forward slash, the character R
, and then a single asterisk, and then add the remaining parenthesis for your list constructor.
02:03
Then hit Enter. In this example, you can see the same items as before are listed, such as realpython, rename_files.py, and request.py. This shows that the call to glob
method with pattern two asterisks, forward slash R
and a single asterisk is equivalent to the .rglob()
method with the R
and single asterisk.
02:26
That being said, the .rglob()
method is a slightly more explicit version of calling glob with a recursive pattern, so it’s typically better to practice using the more explicit version instead of using recursive patterns with the normal glob
method.
02:41
You’ve learned a lot about glob patterns and conditional listing using the glob
methods. Next up, you’ll learn how to do advanced matching with the glob
methods.
Become a Member to join the conversation.