Getting Only Files With Loops and Conditionals
00:00 In this lesson, you’ll learn how to get only files with loops and conditionals.
00:06
As with all generators, you can use a for
loop to iterate over each item that the generator yields. This will give you a chance to explore some of the properties of each object.
00:15
For example, you can determine if the object is a directory or a file. You can use the method .isdir()
to determine if the item is a directory and .isfile()
to determine if the item is a file.
00:28
You can head over to the code to try this out now. For this lesson and following lessons, make sure you have started with pathlib
imported in your desktop variable set to your desktop path.
00:40
If you haven’t done this yet, please be sure to reference the previous lesson to see how. Starting with pathlib
already imported and desktop already set to your path, you can now start with your for loop. for item
in desktop.iterdir()
, colon, and hit Enter.
01:02
And then within the for
loop body, you can add an f-string to display some information about each item. You can start by typing print(f"
and then curly braces and inside those curly braces type item
.
01:18
Then move outside those braces and then add a dash space and then a new set of curly braces. Inside this set, single quotes and inside of that add dir
space if item.is_dir()
else single quotes file
.
01:39
And then on the outside of that curly brace, end it off with the double quotes and then close it off with a parenthesis. The line dir
if item.is_dir()
else file
is a conditional expression.
01:53
It’ll print dir
if the item is a directory or file
if it isn’t a directory. Go ahead and hit Enter.
02:03
You can see you’re now getting back a list of items with a dash indicating whether the item is a directory or file. For example, you may see desktop.ini - file, Notes -dir
, realpython -`dir, and more.
02:17
You can filter specifically by files within your for loop body. Start by typing for item in desktop.iterdir():
02:29
enter, and inside the for loop body add if item.is_file():
02:38
enter and type print(item)
. Now the item will only print if the item is a file. Go ahead and hit Enter. You only printed files in this case, desktop.ini, and todo.txt.
02:53
Another option is to place generators into comprehensions. So try this out now, start by typing square bracket item for item in
desktop.iterdir()
if item.is_dir()
03:14 and then close it off with the remaining square bracket. Go ahead and hit Enter.
03:19 You are now only seeing your directory items. For example, the Notes directory, realpython, and scripts. But what if you need all the files and directories in the sub-directories of your folder too?
03:30
You can adapt iterdir()
as a recursion function. You’ll learn how to do this in a later tutorial, but first you may be better off using .rglob()
, which we’ll get to next.
Become a Member to join the conversation.