56 lines
1.7 KiB
Python
56 lines
1.7 KiB
Python
import os
|
|
from pathlib import Path
|
|
|
|
def ensure_folder_exists(folder_path):
|
|
"""
|
|
Check if a folder exists and create it if it doesn't.
|
|
|
|
Args:
|
|
folder_path (str or Path): Path to the folder to check/create
|
|
|
|
Returns:
|
|
bool: True if folder was created, False if it already existed
|
|
|
|
Raises:
|
|
OSError: If folder creation fails due to permissions or other issues
|
|
"""
|
|
folder_path = Path(folder_path)
|
|
|
|
if folder_path.exists():
|
|
if folder_path.is_dir():
|
|
return False # Folder already exists
|
|
else:
|
|
raise OSError(f"Path '{folder_path}' exists but is not a directory")
|
|
|
|
try:
|
|
folder_path.mkdir(parents=True, exist_ok=True)
|
|
return True # Folder was created
|
|
except OSError as e:
|
|
raise OSError(f"Failed to create folder '{folder_path}': {e}")
|
|
|
|
# Alternative simpler version using os module
|
|
def ensure_folder_exists_simple(folder_path):
|
|
"""
|
|
Simple version using os.makedirs with exist_ok parameter.
|
|
|
|
Args:
|
|
folder_path (str): Path to the folder to check/create
|
|
"""
|
|
os.makedirs(folder_path, exist_ok=True)
|
|
|
|
# Usage examples
|
|
if __name__ == "__main__":
|
|
# Example 1: Create a single folder
|
|
folder_created = ensure_folder_exists("my_new_folder")
|
|
print(f"Folder created: {folder_created}")
|
|
|
|
# Example 2: Create nested folders
|
|
ensure_folder_exists("data/processed/results")
|
|
|
|
# Example 3: Using the simple version
|
|
ensure_folder_exists_simple("logs/2024")
|
|
|
|
# Example 4: Using with absolute path
|
|
import tempfile
|
|
temp_dir = tempfile.gettempdir()
|
|
ensure_folder_exists(os.path.join(temp_dir, "my_app", "cache")) |