I am confused to use about these two os
methods to create the new directory.
Please give me some example in Python.
The os. makedirs() method is used to create a directory recursively in the os module using Python. It is similar to the method os. mkdir() with the addition that it also creates intermediate directories to create leaf directories.
Creating a directory is a common operation in Python when you're working with files. The os. mkdir() method can be used to create a single directory, and the os. makedirs() method can be used to create multi-level directories.
os.mkdir(path[,mode]) path is the path where you want to complete the new directory. mode is the mode of the directory to be given. The default mode is 0777 ( o c t a l ) 0777 (octal) 0777(octal).
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.
makedirs()
creates all the intermediate directories if they don't exist (just like mkdir -p
in bash).
mkdir()
can create a single sub-directory, and will throw an exception if intermediate directories that don't exist are specified.
Either can be used to create a single 'leaf' directory (dirA):
os.mkdir('dirA')
os.makedirs('dirA')
But makedirs must be used to create 'branches':
os.makedirs('dirA/dirB')
will work [the entire structure is created]mkdir
can work here if dirA
already exists, but if it doesn't an error will be thrown.
Note that unlike mkdir -p
in bash, either will fail if the leaf already exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With