in this article, We will learn to create a Directory in Python. Python has an OS module that will help manage, create, remove, read and write directories, and files.
Python OS Module
Python’s standard utility modules include the OS module. The OS module allows you to use operating system-dependent functions on the go.
An OS module in Python can be used to manage, create, remove, read and write directories, files, and so on.
We can use OS modules to accomplish a variety of tasks, such as creating a directory, determining the current location of a directory, renaming a directory, changing the directory, and so on.
How To Import OS Module
We can import os module as usual like other modules import in a python application.
import os
There are two main methods available in the OS module for creating a directory. These are the following.
- os.mkdir()
- os.makedirs()
I have already shared the tutorial How To Delete File If Exists In Python and How To Delete a Directory In Python.
os.mkdir() method to Create a Directory in Python
The os module has in-built os.mkdir()
method to create a directory in the system. This method raises FileExistsError if the directory to be created already exists.
Syntax:
os.mkdir(path, mode = 0o777, *, file_descriptor = None)
- path (required): Where we want to create a directory.
- mode (optional): It is an integer value representing a mode of a directory to be created.
- file_descriptor (optional): This parameter has the value None by default. The file descriptor parameter is ignored if the path is absolute.
Example:
import os dir = 'pythonpip' try: os.mkdir(dir) print("Directory ", dir, "is created Successfully.") except FileExistsError: print("Directory ", dir, " already exists")
Output
Directory pythonpip is created Successfully.
The os.mkdir(path) command just creates the supplied directory; it does not generate any intermediary directories in the path.
Like if you want to create a directory inside the directory, and both directories do not exist, then it won’t create any directory.
So, You can solve the above problems using os.makedirs() method.
os.makedirs() method to Create a Directory in Python
The os.makedirs()
is used to recursively construct a directory. That is, if any intermediate-level directory is missing while creating the leaf directory, the os. makedirs()
method will construct all of them.
Syntax:
os.makedirs(path)
- path (required): Where we want to create a directory.
The os.makedirs(name) command will create a directory on a given path, as well as any intermediate-level directories that don’t exist.
Example:
import os dir = 'pythonpip/dev/script' try: os.makedirs(dir) print("Directory ", dir, "is created Successfully.") except FileExistsError: print("Directory ", dir, " already exists")
Output:
This will create dev and script directory under the pythonpip directory.
One thought to “Create a Directory in Python With Example”