function ensure_dir_exists
Creates a directory and all necessary parent directories if they don't already exist, with logging support.
/tf/active/vicechatdev/msg_to_eml.py
1293 - 1298
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
oslogging
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function ensure_dir 88.3% similar
-
function ensure_directories 71.4% similar
-
function ensure_path_exists 70.9% similar
-
function ensure_document_folders 58.1% similar
-
function check_file_exists 56.9% similar