Creating a Subdirectory
No complaints. The path shows up beautifully. But now if you want to create this directory, you’ll run into an error.
monthly_dir.mkdir() gives you a
FileNotFoundError because, while the notes directory exists, you did not yet create the plans directory. In general, to be able to create a directory, all the parent directories need to already exist. However, there’s a different way of doing it by setting another parameter to
then you see that Python doesn’t complain, and
monthly_dir does now exist. So all the intermediate subfolders—in this case, it’s only one, called
"plans"—get created if you pass
.mkdir(). So putting these two things together, the one you saw before about
parents gives you a common pattern when creating directories using Python’s
pathlib module. Let’s make a new directory.
For example, if you want a user to pass a certain path, you might want to double check that the path already exists and that they’re not accidentally mistyping the path that they wanna save a file to, for example, just by adding an accidental typo. But you’ll commonly see, and probably also commonly use, this pattern of using
True. All right, enough with folders. In the next lesson, you’ll learn how to create files using
Become a Member to join the conversation.