🔍 Code Extractor

function ensure_dir

Maturity: 53

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

File:
/tf/active/vicechatdev/CDocs/utils/__init__.py
Lines:
244 - 260
Complexity:
simple

Purpose

This utility function ensures that a specified directory path exists in the filesystem. It handles the creation of nested directories (similar to 'mkdir -p' in Unix) and provides error handling with logging. It's commonly used in file I/O operations where output directories need to be guaranteed to exist before writing files. The function is idempotent - calling it multiple times with the same path is safe.

Source Code

def ensure_dir(directory: str) -> bool:
    """
    Ensure directory exists, creating it if necessary.
    
    Args:
        directory: Directory path
        
    Returns:
        Boolean indicating success
    """
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
        return True
    except Exception as e:
        logger.error(f"Error creating directory {directory}: {e}")
        return False

Parameters

Name Type Default Kind
directory str - positional_or_keyword

Parameter Details

directory: A string representing the absolute or relative path to the directory that should exist. Can include nested paths (e.g., 'path/to/nested/dir'). The function will create all intermediate directories if they don't exist. Empty strings or invalid path characters may cause exceptions.

Return Value

Type: bool

Returns a boolean value: True if the directory exists or was successfully created, False if an exception occurred during directory creation (e.g., permission denied, invalid path, disk full). The function catches all exceptions and logs errors before returning False.

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(directory: str) -> bool:
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
        return True
    except Exception as e:
        logger.error(f"Error creating directory {directory}: {e}")
        return False

# Usage examples
if ensure_dir('./output/reports'):
    print("Directory ready for use")
    # Now safe to write files to ./output/reports
    with open('./output/reports/data.txt', 'w') as f:
        f.write('Sample data')
else:
    print("Failed to create directory")

# Check nested paths
ensure_dir('/tmp/my_app/data/processed/2024')

# Idempotent - safe to call multiple times
ensure_dir('./existing_dir')
ensure_dir('./existing_dir')  # Returns True, no error

Best Practices

  • Always check the return value to ensure the directory was created successfully before attempting to write files
  • Ensure a logger is properly configured before using this function, as it relies on a module-level 'logger' variable
  • Use absolute paths when possible to avoid ambiguity about the working directory
  • Be aware that this function catches all exceptions, which may mask specific permission or disk space issues - check logs for details
  • The function uses os.makedirs() which creates all intermediate directories, similar to 'mkdir -p' in Unix
  • Consider using pathlib.Path for more modern path handling in new code, though this function works well for backward compatibility
  • In multi-threaded environments, be aware of potential race conditions between the exists check and makedirs call (though os.makedirs handles this gracefully in most cases)

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function ensure_dir_exists 88.3% similar

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

    From: /tf/active/vicechatdev/msg_to_eml.py
  • function ensure_path_exists 69.6% 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_directories 64.5% 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_document_folders 53.8% 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 52.1% 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