SoFunction
Updated on 2025-03-04

python makedirs recursively create directory

In Python, the() function is used to recursively create directories. That is, it will not only create the specified directory, but also any necessary parent directory. This function is very useful when dealing with the need to create a multi-level directory structure.

1. Syntax

(name, mode=0o777, exist_ok=False)

1.1. Parameters

  • name: The target directory path to create, which can be an absolute path or a relative path.
  • mode (optional): Set the permission mode of the directory, the default is 0o777 (octal representation), that is, read, write, and execute permissions are open to all users.
  • exist_ok (optional): If True, no exception is raised when the target directory already exists; if False (default), a FileExistsError exception is raised when the target directory already exists.

1.2. Return value

  • The function does not return a value.

1.3. Example

1.3.1. Basic usage

import os
# Create a single-level directory('test_dir')
# Create multi-level directory('parent_dir/child_dir/grandchild_dir')

1.3.2. Use mode parameters

import os
# Create a directory and set permissions to 0o755('secure_dir', mode=0o755)

1.3.3. Use the exist_ok parameter

import os
# Create a directory, if the directory already exists, no exception will be raised('existing_dir', exist_ok=True)

1.3.4. Error handling

If the target directory already exists and the exist_ok parameter is False, a FileExistsError exception will be raised:

import os
try:
    ('existing_dir')
except FileExistsError:
    print("Directory already exists")

2. Practical application

The () function is very useful when you need to ensure that the directory structure exists, for example before a file write operation:

import os
def save_file(file_path, content):
    # Extract directory path    dir_path = (file_path)
    # Create a directory (if it does not exist)    (dir_path, exist_ok=True)
    # Write to a file    with open(file_path, 'w') as file:
        (content)
#User Examplesave_file('data/output/', 'Hello, world!')

By using the () function, you can easily create the required directory structure, thereby avoiding the tedious process of manually checking and creating directories, and improving the simplicity and maintainability of your code.

This is the end of this article about python makedirs() recursively creating a directory. For more related python makedirs() to create a directory, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!