Dealing with files and directories is a common task in Python programming. Whether you’re organizing data or storing results, creating directories is integral to file management. In this post, we’ll explore how to create directories in Python using built-in functions like os.mkdir(), os.makedirs(), and pathlib.Path.mkdir(). By the end of this guide, you’ll have a solid understanding of directory creation in Python, enhancing your file handling skills. Let’s dive in!

The os.mkdir() function in Python is a built-in method used to create a directory. This function is part of the os module, which provides a portable way of using operating system-dependent functionality.

Definition

os.mkdir(path, mode=0o777, *, dir_fd=None)
  • path: A string representing the directory to be created.
  • mode: (Optional) The mode (permissions) to set for the new directory. The default is 0o777 (octal), which means the directory is readable, writable and searchable by all users.
  • dir_fd: (Optional) If provided, the function will operate relative to this directory descriptor.

Usage

The os.mkdir() function is used when you want to create a single directory. If the directory already exists, the function will raise a FileExistsError.

Here is a simple example:

import os

# Specify the path
path = "new_directory"

# Create the directory
os.mkdir(path)

print(f"Directory '{path}' created")

This code will create a new directory named ‘new_directory’ in the current working directory. If the directory already exists, an error will be raised.

Create If Not Exists

To create a directory using os.mkdir() only if it doesn’t already exist, you can use the os.path.exists() function to check if the directory is already there. Here’s an example:

import os

# Specify the path
path = "new_directory"

# Check if the directory exists
if not os.path.exists(path):
    # Create the directory
    os.mkdir(path)
    print(f"Directory '{path}' created")
else:
    print(f"Directory '{path}' already exists")

In this code, os.path.exists(path) returns True if the path (directory or file) exists and False if it doesn’t. So, the directory will only be created if it doesn’t already exist.

Using os.makedirs()

The os.makedirs() function also creates a directory but, unlike os.mkdir(), it can create all the intermediate-level directories needed to create the final directory. If the directory already exists and exist_ok is set to False, it will also raise a FileExistsError.

import os

# Specify the path
path = "dir/sub_dir"

# Create the directories
os.makedirs(path)

print(f"Directory '{path}' created")

This code creates a directory named ‘dir’ and a subdirectory within it named ‘sub_dir’. Even if ‘dir’ does not exist, os.makedirs() will create it along with ‘sub_dir’. If the directories already exist, it will raise an error unless exist_ok is set to True.

When to use one over the other

It’s easy to always use os.makedirs() to create directories, right? After all, if you are unsure about the directory structure you are dealing with, it can always create all the intermediary directories.
However, this is not a good thing in my opinion. This feature leaves the door open for uncertainties about how the data is organized on your disk. Which can lead to errors when trying to read back the data. You must always be aware of the directory structure and where every bit of data lies on your disk.

So Instead of always using os.makedirs(), only use it when you explicitly want to create multiple nested directories. Otherwise, you should try to use os.makedir() whenever possible.

Using pathlib.Path.mkdir()

pathlib is a module in Python for handling filesystem paths. It’s more intuitive and easier to use than os.mkdir() or os.makedirs(). The Path.mkdir() method in pathlib creates a new directory at the given path.

Here’s how you can use it:

from pathlib import Path

# Specify the path
path = Path('new_directory')

# Create the directory
path.mkdir(parents=True, exist_ok=True)

In this code:

  • Path('new_directory'): This creates a Path object that represents the directory ‘new_directory’.
  • path.mkdir(parents=True, exist_ok=True): This creates the directory. The parents=True argument means that any missing parent directories will be automatically created (like os.makedirs()). The exist_ok=True argument means that no error will be raised if the directory already exists.

This is equivalent to using os.makedirs() with exist_ok=True, but with a more intuitive interface.

So, if you’re dealing with filesystem paths in your Python code, consider using pathlib for a more Pythonic and user-friendly approach.

Similar Posts