Creating a Directory
In the next lessons, you’ll gain some practical experience on doing things with Python’s
pathlib module. You’ll learn how to create directories and files, iterate over the contents of a directory, search for files and folders, and also how to move and delete files and folders.
00:19 Let’s start off by creating some directories and files.
Let’s start with an import, but this time let’s just directly import the
Path class, which is mainly what you’re using when you work with
So you’ll commonly see something like this
import Path. In this case, I’m just directly importing the
Path class, which is what you’re mostly working with and which saves you a little bit of typing.
You don’t always have to put the namespace of
pathlib in front of it when you’re working with a
Path object. Now I want to create a new directory, and let’s say I want to keep track of my notes somewhere.
So I’ll say I want to create a notes director, and I’ll put it right into my home directory. So, you already know I can say
Path.home(), and then following that, I’ll create a directory called
01:17 All right, does this notes directory exist?
Of course it doesn’t. But now I can go ahead and say,
notes_dir.mkdir(), which stands for make directory. And after I run this method, I’m going ask again, does
notes_dir.exists()? And now it’s here. So go ahead, pause the video if you’re following along, and open up your home directory to confirm that the notes directory is actually there. You will see a directory called
notes sitting in your home directory.
So this is a way that you can create a directory using Python’s
pathlib module. But let’s try what happens if you would call the same method again.
So I would say
notes_dir.mkdir() another time. Then you see you get a
FileExistsError, and it tells me that this file—in this case, the file is a folder—already exists.
So if you call it with a path that exists, then this is going to run into an error. Now, if you want to avoid this, and let’s say you write a script that should create a folder, but if the folder’s there already, you don’t really want it to exit with an error message, then you can pass a parameter to
It looks like this:
notes_dir.mkdir and then you can add
exist_ok=True. You can see in this little pop-up that
exist_ok is by default
False, but if you set it to
True, then you won’t run into an error if the directory already exists.
True is essentially the same as saying,
if not notes_dir.exists():
03:19 But doing it with the parameter is quicker and easier to read. Now what happens if you want to create a directory inside of another directory, where the parent directory doesn’t yet exist?
03:32 So let me clear the screen and then we’ll try that out next.
Become a Member to join the conversation.