How to Create a Directory in Python

Create A Directory In Python Thumbnail

Python was used to create a wide variety of applications, some of which required the creation of a directory to run on the system. For example, if you are installing an application, you see that many directories are automatically created to store that application data, you don’t need to create that.

In the same way, you can write code to create the directories and put that in your application so that it can create directories automatically to store data.

In this tutorial, we will see how to do precisely that. We will learn several ways to create a directory in Python.

Steps to Create a Directory in Python

Python os module is a module used to deal with and interact with the underlying operating systems and the files.

The os module contains various in-built methods to create directories in the system. Among them, the popular ones are the mkdir() method and the makedirs() method in Python.

To use os module methods, we need to import it using the below syntax:

import os 

Now, once you have imported it into your Python project, you can use its methods mkdir() and makedirs() to create a directory, let’s go through them one by one so that you can choose them accordingly.

Using os.mkdir() method to Create a Directory in Python

The mkdir() method is used to create a directory on a specific path, if any of the parent directories are not present as mentioned in the path, then this method throws an error “FileNotFoundError”.

This is why mkdir() method is recommended to use only in places where you are sure that the directories mentioned in the specified path are already present.

Syntax:

os.mkdir(path, mode)
  • path: The location wherein the user wants the directory to be created. It is a string or byte value that includes the entire path and name of the directory to be built.
  • mode: The permissions that must be given to deal with the file operations within the directory. The default value is ‘0o777‘.

Example 1: Create a Directory using Python in the specified location.

 import os 

main_dir = "C:/Practice"

os.mkdir(main_dir) 
print("Directory '% s' is built!" % main_dir) 

Output:

Directory 'C:/Practice' is built!
Creating a directory using mkdir()
Created a directory using mkdir()

Example 2: Providing permissions for read and write operations within the directory.

import os 

main_dir = "C:/JournalDev"

os.mkdir(main_dir,mode = 0o666) 
print("Directory '% s' is built!" % main_dir) 

Setting mode = 0o666 allows read and write file operations within the created directory.

Output:

Directory 'C:/JournalDev' is built!
Creating a directory using mkdir() with read and write permission
Created a directory using mkdir() with read and write permission

Exceptions with os.mkdir() method

The os.mkdir() method raises a FileExistsError Exception if the new directory we want to create already exists in the folder specified.

Example:

Let’s try to create a new directory in the path where the target directory already exists.

import os 

main_dir = "C:/JournalDev"

os.mkdir(main_dir,mode = 0o666) 
print("Directory '% s' is built!" % main_dir) 

Output:

FileExistsError                           Traceback (most recent call last)
<ipython-input-17-75731447cf21> in <module>
      3 main_dir = "C:/JournalDev"
      4 
----> 5 os.mkdir(main_dir,mode = 0o666)
      6 print("Directory '% s' is built!" % main_dir)
      7 

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:/JournalDev'

Here the mkdir() method throws an error as the directory already exists.

Using os.makedirs() method to Create a Directory in Python

The problem with the mkdir() method is that it must that the parent directories mentioned in the path are already present, if not it will raise an error “FileNotFoundError”.  There can be many cases where we strictly need to create a directory on the specific path and if any of the parent directories are not present we want it to automatically gets created. Here comes the makedirs() method.

The makedirs() method can create all the intermediate directories as well as the leaf directories if they don’t exist in the specified path.

Syntax:

os.makedirs(path,mode)
  • path: The location wherein the user wants the directory to be created. It is a string or byte value that includes the entire path and name of the directory to be built.
  • mode: The permissions that must be given to deal with the file operations within the directory. The default value is ‘0o777‘.

Example:

import os 
main_dir = "C:/Examples/Python_files/OS_module"

os.makedirs(main_dir,mode = 0o666) 
print("Directory '% s' is built!" % main_dir) 

In the above example, the makedirs() method creates the intermediate directories ‘Python_files’ as well as the leaf directory ‘OS_module’ in one shot through the method.

Output:

Directory 'C:/Examples/Python_files/OS_module' is built!
Created a parent directory using makedirs()
Created a parent directory using makedirs()
Created an Intermediate Directory Using makedirs()
Created an Intermediate Directory using makedirs()
Created a Base Directory using makedirs()
Created a Base Directory using makedirs()

Conclusion

In this tutorial, we have seen mkdir() method where a directory will be created if all parent directories specified in the path is present, otherwise, we have another method makedirs() which can create all intermediate-level directory automatically, both method can used in a Python program using OS module. OS module is a built-in module, we just have to write an import statement for using its methods. We hope this tutorial helped you to learn how to create new directories in Python.

Reference

https://docs.python.org/3/library/os.html