All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

How To Create A Directory In Python

Last Updated : Mar 11, 2024

How To Create A Directory 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)
    print("The directory already exist")
  1. Files and directories can be handled by the os module imported by importing it.
  2. The directory name should be entered by the user.
  3. With the isdir() function of the os module, you can check whether the entered directory exists. As a result, a boolean value is returned.
  4. 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.
  5. As soon as the directory has been created, print a success message.
  6. A message indicating that the directory already exists will be printed if the directory has already been entered.

Conclusion :-

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.