Creating a Directory
00:00
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.
00:24
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 pathlib
.
00:33
So you’ll commonly see something like this from pathlib
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.
00:48
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.
01:00
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 "notes"
.
01:17 All right, does this notes directory exist?
01:23
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
exist,
01:41
by typing 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.
01:59
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.
02:07
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.
02:20
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 .mkdir()
.
02:41
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.
03:02
Setting exist_ok
to True
is essentially the same as saying, if not notes_dir.exists():
03:13
only then notes_dir.mkdir()
.
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.