How To Create A Directory In Python
Last Updated : Jul 25, 2023
IN - Python
In this article we will show you the solution of how to create a directory in python, a Python program can create a directory using the os.mkdir() function by passing an argument to the function specifying the path to the directory.
The objective of this tutorial is to demonstrate how to create a directory, using example programs as examples.
The directory can be created permanently or temporarily by Python script by importing different modules.
The OS module is the most used module in Python for creating directories.
In order to create a permanent directory, you need to use this module.
A temporary directory can be created in Python using the tempfile module.
To create a directory in Python, this tutorial demonstrates how to use various OS and tempfile modules. We will now discuss the idea of how to create a directory in python with an example.
Step By Step Guide On How To Create A Directory In Python :-
#Import os module import os #Initialize the directory name dirname = input("Enter the directory name") #Check the directory name exist or not if os.path.isdir(dirname) == False: #Create directory with permission bits os.makedirs(dirname, mode = 00506) #Print success message print("%s directory has been created." % dirname) else: print("The directory already exist")
- Files and directories can be handled by the os module imported by importing it.
- The directory name should be entered by the user.
- With the isdir() function of the os module, you can check whether the entered directory exists. As a result, a boolean value is returned.
- The os module includes a function named makedirs() that creates directories with permission bits according to the parameters. In the mode argument, the permission bits of the directory are represented. In this case, 00506 represents the permission bits for the 'dr-xrw---' group. Permission bits are expressed as octal numbers with a leading zero.
- As soon as the directory has been created, print a success message.
- A message indicating that the directory already exists will be printed if the directory has already been entered.
As a result, we have successfully learned how to create a directory in python with an example.
Using the functions provided by the OS and tempfile modules, we have shown how to create permanent and temporary directories in Python.
It is my hope that after reading this tutorial Python users will be able to create any type of directory.
I hope this article on how to create a directory in python helps you and the steps and method mentioned above are easy to follow and implement.