🔍 Code Extractor

function ensure_dir_exists

Maturity: 40

Creates a directory and all necessary parent directories if they don't already exist, with logging support.

File:
/tf/active/vicechatdev/msg_to_eml.py
Lines:
1293 - 1298
Complexity:
simple

Purpose

This utility function ensures that a specified directory path exists in the filesystem. If the directory doesn't exist, it creates it along with any necessary parent directories. The function is idempotent and safe to call multiple times. It logs directory creation events and returns the directory path for convenient chaining in file operations.

Source Code

def ensure_dir_exists(directory):
    """Ensure a directory exists, creating it if necessary"""
    if not os.path.exists(directory):
        os.makedirs(directory, exist_ok=True)
        logger.info(f"Created directory: {directory}")
    return directory

Parameters

Name Type Default Kind
directory - - positional_or_keyword

Parameter Details

directory: String or path-like object representing the directory path to create. Can be an absolute or relative path. Accepts nested directory structures (e.g., 'parent/child/grandchild'). The function will create all intermediate directories as needed.

Return Value

Returns the same directory path that was passed as input (string or path-like object). This allows for convenient chaining or assignment patterns. The returned path represents a directory that is guaranteed to exist after the function completes successfully.

Dependencies

  • os
  • logging

Required Imports

import os
import logging

Usage Example

import os
import logging

# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

def ensure_dir_exists(directory):
    """Ensure a directory exists, creating it if necessary"""
    if not os.path.exists(directory):
        os.makedirs(directory, exist_ok=True)
        logger.info(f"Created directory: {directory}")
    return directory

# Example usage
output_dir = ensure_dir_exists('./data/output/reports')
print(f"Directory ready: {output_dir}")

# Can be used inline
file_path = os.path.join(ensure_dir_exists('./logs'), 'app.log')

# Works with absolute paths
abs_path = ensure_dir_exists('/tmp/my_app/cache')

Best Practices

  • Ensure the logger object is properly initialized before calling this function to avoid NameError
  • The function uses exist_ok=True in os.makedirs, making it safe for concurrent execution and race conditions
  • Consider wrapping calls in try-except blocks to handle permission errors or invalid path names
  • The function returns the directory path, enabling method chaining: os.path.join(ensure_dir_exists('./data'), 'file.txt')
  • Works with both relative and absolute paths, but be mindful of the current working directory when using relative paths
  • The function will create all intermediate directories in the path automatically
  • No validation is performed on the directory path format - ensure valid path strings are passed to avoid OS-specific errors

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function ensure_dir 88.3% similar

    Creates a directory and all necessary parent directories if they don't already exist, returning a boolean indicating success or failure.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function ensure_directories 71.4% similar

    Creates required directories for the application if they don't already exist, specifically DOCUMENTS_DIR and CHAT_SESSIONS_DIR.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function ensure_path_exists 70.9% similar

    Recursively creates a directory path in FileCloud storage by ensuring all parent directories exist before creating child directories.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function ensure_document_folders 58.1% similar

    Ensures all required folder hierarchies exist in FileCloud storage for a controlled document, creating them if they don't exist.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function check_file_exists 56.9% similar

    Checks if a file exists at the specified filepath and prints a formatted status message with a description.

    From: /tf/active/vicechatdev/email-forwarder/setup_venv.py
← Back to Browse