Python provides different functions in order to be a complete programming language. It provides operating system-related functions like creating a directory for every operating system like Windows, Linux, MacOSX, etc. In order to create a directory, Python provides the os.makedirs() command in order to create a directory.
The makedirs() method is provided by the os module and in order to use it, the os module should be imported. The makedirs() method syntax is like below.
- NAME is the name or complete path of the directory which will be created. This parameter is required.
- MODE is the file mode for the created directory. This parameter is optional.
- EXIST_OK is the parameter is set to True the new directory will be created and overwritten even if it exists. This parameter is optional and the default value is False.
First, we will start with a simple example where create a directory in the current working directory without providing the complete path of the new directory. We will set the name parameter of the makedirs() method. The name will be “backup”.
import os os.makedirs("backup")
In this example, we will create a new directory by providing the full path of the newly-created directory. We will provide the name parameter as the full path which will be “/home/ismail/data“.
import os os.makedirs("/home/ismail/data")
Set Directory Permission For Created Directory
By default, the newly created directory permissions will be inherited from the umask value. These permissions are also called mode which provides like read, write, and execution permissions about the directory. We will specify the mode parameter as “0o654”.
import os mode = 0654 os.makedirs("/home/ismail/data",mode)
Overwrite Directory Even Exist
By default, the makedirs() method will not overwrite if the provided directory exists currently. This is set with the is_exist parameter which is set as False by default. We can set this parameter as True in order to overwrite the existing directory. This can be used if we get an error like
FileExistsError while trying to create a new directory with the previously defined ways.
import os os.makedirs("/home/ismail/data",exist_ok=True)
Create Multilevel Directories
In some cases, we need to create multilevel directories where intermediate-level directories also do not exist. We can use the
os.makedirs() method in order to create directories even if they do not exist. In the following example the directories data, backup, and 2022 are not exist but they will be created automatically.
import os os.makedirs("/home/ismail/data/backup/2022/")