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.
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
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 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.
Become a Member to join the conversation.