Demystifying os.mkdir() in Python

Pankaj Singh Last Updated : 10 Jan, 2024
4 min read

Introduction

Python provides diverse modules that streamline and enhance various tasks, contributing to an even more efficient and enjoyable programming experience. One such task is directory manipulation, and the os module provides a method called mkdir() to create directories. In this blog post, we will delve into the intricacies of os.mkdir() and explore how it can efficiently handle directory creation in Python.

os.mkdir() in Python

Understanding the os.mkdir() in Python

The os.mkdir() method in Python creates a new directory (folder). It belongs to the os module, which provides a way to interact with the operating system.

Here’s a breakdown of how the os.mkdir() method works:

Purpose

  • Creates a new directory (folder) in the specified path.
  • It’s part of the os module, which provides functions for interacting with the operating system.

Syntax

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

Arguments

  • Path: The full path of the directory to be created (as a string).
  • Mode (optional): The permissions mode for the new directory (default is 0o777, which grants full read, write, and execute permissions to all users).
  • dir_fd (optional): A file descriptor referencing an open directory used for relative path creation.

Return Value

  • None

Raises

  • FileExistsError: If the directory already exists.
  • OSError: If there’s an error creating the directory (e.g., insufficient permissions, invalid path).

Example

import os

# Create a directory named "my_new_dir" in the current working directory

os.mkdir("my_new_dir")

# Create a directory with specific permissions

os.mkdir("another_dir", mode=0o755)  # Read and execute for all, write for owner only

Key Points

  • os.mkdir() only creates the last directory in the path. Intermediate directories must already exist.
  • To create an entire directory structure, use os.makedirs() instead.

Handling Exceptions with os.mkdir()

When using the os.mkdir() method, it is important to handle exceptions that may occur during the directory creation process.

Use a Try-except Block

FileExistsError

This exception occurs if you try to create a directory that already exists. You can either ignore it or provide alternative actions.

OSError

This broader exception covers other errors like insufficient permissions or invalid paths. Provide informative error messages or implement recovery strategies.

Import the OS module

import os

Code

os.mkdir("my_new_dir")

except FileExistsError:

    print("Directory already exists.")

except OSError as err:

    print(f"Error creating directory: {err}")

Check for Directory Existence Beforehand Using os.path.exists()

Use os.path.exists() to check if a directory exists before attempting to create it, avoiding unnecessary exceptions.

Code

import os

if not os.path.exists("my_new_dir"):

    os.mkdir("my_new_dir")

else:

    print("Directory already exists.")

Use os.makedirs() For Recursive Creation

Use os.makedirs() to create entire directory structures with intermediate directories, handling errors for the full path.

exist_ok parameter: os.makedirs() accepts an exist_ok=True argument to suppress FileExistsError if the directory already exists, making it more robust.

Code

import os

os.makedirs("path/to/new/directory", exist_ok=True)  
# Creates intermediate directories if needed

Alternative for os.mkdir()

In addition to the os.mkdir() method, Python also provides the os.makedirs() method, which can be used to create multiple levels of directories at once. This method is particularly useful when dealing with complex directory structures. Let’s take a look at its overall syntax & use:-

Syntax

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

Arguments

  • path: The full path of the directory structure to create (as a string).
  • mode (optional): The permissions mode for the new directories (default is 0o777, full read, write, and execute permissions for all users).
  • exist_ok (optional): If True, suppresses the FileExistsError if the target directory already exists (default is False).

Return Value

  • None

Raises

  • FileExistsError: If the target directory already exists and exist_ok is False.
  • OSError: If there’s an error creating any of the directories (e.g., insufficient permissions, invalid path).

Example

import os

# Create the directory structure "data/subfolder1/subfolder2"

os.makedirs("data/subfolder1/subfolder2")

# Create the same structure, but don't raise an error if it already exists

os.makedirs("data/subfolder1/subfolder2", exist_ok=True)

Conclusion

In this blog, we explored the os.mkdir() method in Python and learned how it can be used to create new directories. We discussed the syntax of the method, how to handle exceptions, and also looked at an alternative method, os.makedirs(). By mastering the os.mkdir() method, developers can efficiently manage directory creation tasks in their Python programs.

Unlock your potential! Enroll now in our Introduction to Python course. No coding experience is needed. Power up your career with Python and kickstart your journey into Data Science. Start today!

FAQs

1. What is the difference between os.mkdir and os.makedirs in Python?

A. os.mkdir is used to create a single directory, while os.makedirs is used to create a directory and any necessary parent directories that do not exist.

2. How can I use os.mkdir to create a directory in Python 3?

A. To use os.mkdir, you need to import the os module and then call os.mkdir(“directory_name”) where “directory_name” is the name of the directory you want to create.

3. When should I use os.makedirs instead of os.mkdir?

A. Use os.makedirs when you need to create a directory along with its parent directories. If the parent directories don’t exist, os.makedirs will create them recursively.

4. What happens if I try to use os.mkdir to create a directory that already exists?

A. If you use os.mkdir to create a directory that already exists, a FileExistsError will be raised. It’s a good practice to check whether the directory exists before attempting to create it.

5. Can I specify a full path when using os.mkdir or os.makedirs?

A. Yes, you can provide a full path as an argument to os.mkdir or os.makedirs. If the specified path contains nonexistent parent directories and you’re using os.makedirs, it will create them. Ensure that you have the necessary permissions to create directories at the specified location.

Hi, I am Pankaj Singh Negi - Senior Content Editor | Passionate about storytelling and crafting compelling narratives that transform ideas into impactful content. I love reading about technology revolutionizing our lifestyle.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details