Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

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.

alphafox28js on Dec. 7, 2023

Still returning a FileExistsError:

from pathlib import Path

# Will not return true because there is no notes directory.
# notes_dir = Path.home() / 'notes'
# notes_dir.exists()

# This will create the Directory
# notes_dir.mkdir()
# notes_dir.exists(): Checks if File Exists, Returns False/True

practice_python_dir = Path.home() / 'scratchpad'

practice_python_dir.mkdir()
practice_python_dir.exists()
practice_python_dir.is_dir()

# To Avoid getting a "FileExistsError" when running more than once, use the below:
practice_python_dir.mkdir(exist_ok=True)

if not practice_python_dir.exists():
    practice_python_dir.mkdir()

alphafox28js on Dec. 7, 2023

Even putting the code before the creation of directory, still populates the same error:

from pathlib import Path

# Will not return true because there is no notes directory.
# notes_dir = Path.home() / 'notes'
# notes_dir.exists()

# This will create the Directory
# notes_dir.mkdir()
# notes_dir.exists(): Checks if File Exists, Returns False/True

practice_python_dir = Path.home() / 'scratchpad'

# To Avoid getting a "FileExistsError" when running more than once, use the below:
practice_python_dir.mkdir(exist_ok=True)

if not practice_python_dir.exists():
    practice_python_dir.mkdir()

practice_python_dir.mkdir()
practice_python_dir.exists()
practice_python_dir.is_dir()

alphafox28js on Dec. 7, 2023

To Correct the Above Issues for anyone reading this experiencing the same frustation ahaha ;) use the following as an exmample:

from pathlib import Path

# Will not return true because there is no notes directory.
# notes_dir = Path.home() / 'notes'
# notes_dir.exists()

# This will create the Directory
# notes_dir.mkdir()
# notes_dir.exists(): Checks if File Exists, Returns False/True

practice_python_dir = Path.home() / 'scratchpad'

# To Avoid getting a "FileExistsError" when running more than once, use the below:
# Can also use the try / except handling rules.
practice_python_dir.mkdir(exist_ok=True)

if not practice_python_dir.exists():
    practice_python_dir.mkdir()

# practice_python_dir.mkdir() //uncommenting this line will throw a FileExistError.
practice_python_dir.exists()
practice_python_dir.is_dir()

Martin Breuss RP Team on Dec. 7, 2023

@alphafox28js ah yes, nice job figuring it out. To sum it up for other learners: the issue here was calling .mkdir() multiple times, and not passing exist_ok=True in each of the calls.

So, once you create the directory with one call of .mkdir(), you’ll get the FileExistsError if you call the method again anywhere in your code. Unless you pass exist_ok=True or wrap it in the conditional statement that @alphafox28js is showing above.

Become a Member to join the conversation.