As usual, there are a few different ways of doing this. With the
os module, if you want to create just a single directory, you can use
os.mkdir() (make directory) with the directory name, which creates a single subdirectory with the given name.
Important to note is that this will not create a directory and subdirectories. If you need that, you need to use
os.makedirs() and then you can pass in a full
path_name with multiple subdirectories and it will create that full directory tree, as needed.
Okay, let’s make some directories!
os.mkdir() is the first and the most basic way to do this. As you can see, it takes in a
path parameter, and then it can also take in a
mode parameter, and then
01:13 I won’t get into, really, how these work directly, just know that this has to do with file permissions, and then what to do if you have symbolic links or something else like that in your directory.
If I need to do something like that I can use
os.makedirs() which will make this directory, and then it will make all of these, it will just make everything that I need in order to get this final directory.
then you can see that it has the
'sub_test' folder, just as I needed. So, that’s really pretty simple and awesome. The reason that
mkdir() exists in this way, and the reason that it has this behavior is just to really be, kind of, a safety valve, a safety mechanism, to make sure that you really know exactly what’s going on with your filesystem at all times.
makedirs() is awesome, but it can also cause unexpected behavior if you think you’re in one directory and you make a whole chain of subdirectories, and then you end up in a totally unexpected place, whereas
mkdir() is built to, kind of, error out before that happens.
03:30 Now, the issue with this, of course, is that this just ends up doing nothing because it doesn’t make a directory, because it already exists. It just doesn’t tell you that loudly, it just, kind of, silently suppresses that error.
03:42 That’s definitely something that’s important to note, is that even if you don’t want that error to happen, you probably still wanted to know that something is happening there because otherwise, you could run into problems where you think you’re creating something new, but really you’re trying to create something, and there’s already an existing directory.
03:59 So, this behavior, you can eliminate if you need it, but you might not want to at all times. So, those are the different ways to create directories in Python, and I think it’s really pretty simple and straightforward.
Become a Member to join the conversation.