How Python Make Directory with Examples

In this article, we will discuss how Python makes a directory with the help of examples.

From the basics of creating directories to handling common errors, we’ll cover everything you need to know.

Now let’s get started!

What is a Directory in Python?

In Python, a directory is a folder that contains files and other directories. It acts as a container for organizing and managing data in a hierarchical structure.

Directories provide a systematic way to group related files, making it easier to access and maintain them.

Creating a directory in Python

To create a directory in Python, you can use the os module, which provides various functions for interacting with the operating system. The os.makedirs() function allows you to create directories recursively, ensuring that all intermediate directories are also created if they don’t exist.

Below are several approaches for creating a director within the OS module:

  • os.mkdir()
  • os.makedirs()

os.mkdir() python

Python’s os.mkdir() method is used to create a directory named path with the given mode. This method raises FileExistsError if the specified directory already exists.

Syntax:

os.mkdir(path, mode = 0o777, *, dir_fd = None)

Parameter:

  • path: An object resembling a path that represents a file system path. A string or bytes object expressing a path constitutes a path-like object.
  • mode(optional): A positive integer indicating the mode of the directory to be created. If this argument is missing, Oo777 is used as the default value.
  • dir_fd (optional): A file descriptor that specifies a directory. This parameter’s default value is None. If the path supplied is absolute, dir_fd is disregarded.

Note: The asterisk (*) in the parameter list indicates that any subsequent arguments (in this case, “dir_fd”) are keyword-only parameters and must be supplied by name, not as positional parameters.

  • Return Type: This method does not return any value.

Example

import os

# Directory
directory = "PythonForFree"

# Parent Directory path
parent_dir = "D:/Pycharm projects/"

# Path
path = os.path.join(parent_dir, directory)

os.mkdir(path)
print("Directory '% s' created" % directory)


directory = "PFF"

# Parent Directory path
parent_dir = "D:/Pycharm projects"

# mode
mode = 0o666

# Path
path = os.path.join(parent_dir, directory)

os.mkdir(path, mode)
print("Directory '% s' created" % directory)

Output

Directory 'PythonForFree' created
Directory 'PFF' created

python os.makedirs()

Python’s os.makedirs() method is used to build a directory recursively. Thus, if any intermediate-level directories are missing while creating a leaf directory, the os.makedirs() method will construct them all.

For example, consider the following path:

D:/Pycharm projects/PythonForFree/Authors/Nym

Suppose we wish to make the directory ‘Nym’, but the Directories ‘PythonForFree’ and ‘Authors’ do not exist on the path. The os.makedirs() method will then create all missing or inaccessible directories in the supplied path. The ‘PythonForFree’ and ‘Authors’ directories will be generated initially, followed by the ‘Nym’ directory.

Syntax:

os.makedirs(path, mode = 0o777, exist_ok = False)

Parameter:

  • The first argument of this function is required and specifies the directory’s path.
  • This function’s second optional argument is used to set the directory’s permissions for various users.
  • The third argument is not required. If the specified directory already exists, OSError will be displayed.
  • This function does not return anything.

Example

# Python program to explain os.makedirs() method

# importing os module
import os

# Leaf directory
directory = "Nym"

# Parent Directories
parent_dir = "E:/Pycharm projects/PythonForFree/Authors"

# Path
path = os.path.join(parent_dir, directory)

# Create the directory
# 'Nym'
os.makedirs(path)
print("Directory '% s' created" % directory)

# Directory 'PythonForFree' and 'Authors' will
# be created too
# if it does not exists


# Leaf directory
directory = "c"

# Parent Directories
parent_dir = "E:/Pycharm projects/PythonForFree/a/b"

# mode
mode = 0o666

path = os.path.join(parent_dir, directory)

# Create the directory 'c'

os.makedirs(path, mode)
print("Directory '% s' created" % directory)

# 'PythonForFree', 'a', and 'b'
# will also be created if
# it does not exists

# If any of the intermediate level
# directory is missing
# os.makedirs() method will
# create them

# os.makedirs() method can be
# used to create a directory tree

Output

Directory 'Nym' created
Directory 'c' created

How do you create a directory in Python?

Python’s os. makedirs() method is used to build a recursive directory. This means that if any intermediate directories are missing while creating a leaf directory, the os. makedirs() method will create them all.

What is the Dir function in Python?

The dir() function returns all properties and methods without their associated values. This function will return all properties and methods, including those that are inherent to the object type.

Python Make Directory Advanced Techniques

1. Creating Nested Directories

Python allows you to create nested directories by specifying a path that includes multiple directory names separated by slashes (“/”). This is useful when you need to organize data into a hierarchical structure.

import os

# Replace "path/to/nested/directory" with the desired nested directory path
nested_directory_path = "path/to/nested/directory"

try:
    os.makedirs(nested_directory_path)
    print("Nested directory created successfully.")
except OSError as e:
    print(f"Error: {e}")

2. Getting the Current Working Directory

The current working directory is the directory from which your Python script is being executed. You can retrieve the current working directory using the os.getcwd() function.

import os

current_directory = os.getcwd()
print(f"The current working directory is: {current_directory}")

3. Changing the Working Directory

If you need to change the working directory in Python, you can use the os.chdir() function. This is helpful when you want to perform operations in a specific directory.

import os

# Replace "path/to/new/working/directory" with the desired working directory path
new_working_directory = "path/to/new/working/directory"

try:
    os.chdir(new_working_directory)
    print(f"Working directory changed to: {os.getcwd()}")
except OSError as e:
    print(f"Error: {e}")

Conclusion

The ways of creating permanent and temporary directories in Python have been shown in this tutorial by using the functions of OS modules.

  • Use the os.mkdir() function to make a new directory.
  • Use os.makedirs() method to build a recursive directory.

I hope you’ve learned a lot from this. If you have any questions, please leave a comment below. For more Python tutorials, kindly visit our website.

Thank you!

Leave a Comment