Created
October 20, 2025 08:19
-
-
Save pleabargain/ee4468b3933cddda1877d51ac1a0e91a to your computer and use it in GitHub Desktop.
Scans the specified directory and replaces whitespace in item names with dashes. python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import re | |
| import sys | |
| def rename_items(directory, perform_rename=False): | |
| """ | |
| Scans the specified directory and replaces whitespace in item names with dashes. | |
| :param directory: The directory path to scan. | |
| :param perform_rename: If True, actually renames the files/folders. If False (preview mode), | |
| it only prints the proposed changes. | |
| """ | |
| script_name = os.path.basename(sys.argv[0]) | |
| # 1. Get the list of items in the current directory | |
| try: | |
| # os.listdir is used to iterate over files in the current directory | |
| items = os.listdir(directory) | |
| except FileNotFoundError: | |
| print(f"Error: Directory not found at {directory}") | |
| return | |
| except PermissionError: | |
| print(f"Error: Permission denied for directory {directory}") | |
| return | |
| renamed_count = 0 | |
| print("-" * 50) | |
| print(f"{'EXECUTING RENAME' if perform_rename else 'PREVIEW MODE'}") | |
| print("-" * 50) | |
| for name in items: | |
| # Skip the script file itself | |
| if name == script_name: | |
| print(f"Skipping script file: '{name}'") | |
| continue | |
| old_path = os.path.join(directory, name) | |
| # NEW: Skip if the item is a directory (folder) | |
| if os.path.isdir(old_path): | |
| print(f"Skipping folder: '{name}'") | |
| continue | |
| # FIX/Safety Check: Ensure the item is accessible/valid before processing. | |
| # This addresses issues with system links or inaccessible items. | |
| if not os.path.exists(old_path) and not os.path.islink(old_path): | |
| print(f"Skipping inaccessible item: '{name}'") | |
| continue | |
| # Regex: \s+ matches one or more whitespace characters (space, tab, newline) | |
| # and replaces them all with a single dash (-). | |
| new_name = re.sub(r'\s+', '-', name) | |
| if new_name != name: | |
| new_path = os.path.join(directory, new_name) | |
| # Check if the target name already exists | |
| if os.path.exists(new_path): | |
| print(f"WARNING: Skipping '{name}'. Target name '{new_name}' already exists.") | |
| continue | |
| # Perform the action based on the mode | |
| if perform_rename: | |
| try: | |
| os.rename(old_path, new_path) | |
| print(f"RENAMED: '{name}' -> '{new_name}'") | |
| renamed_count += 1 | |
| except OSError as e: | |
| # Catch specific OS errors during rename (e.g., file in use, permission) | |
| print(f"ERROR renaming '{name}': {e}") | |
| else: | |
| # Preview mode | |
| print(f"PREVIEW: '{name}' -> '{new_name}'") | |
| if not perform_rename: | |
| print("\n--- Preview complete. No files were renamed. ---") | |
| else: | |
| print(f"\n--- Renaming complete. {renamed_count} item(s) renamed. ---") | |
| if __name__ == "__main__": | |
| current_dir = os.getcwd() | |
| # --- Pre-run Information and Confirmation --- | |
| print("\n" + "="*50) | |
| print("--- Python Whitespace Renaming Utility ---") | |
| print(f"Scanning directory: {current_dir}") | |
| # UPDATED INSTRUCTIONS | |
| print("This script will replace all **whitespace** in **file names only** with a single hyphen (-).") | |
| print("Folders will be skipped.") | |
| print("First, it will show a **PREVIEW** of all proposed changes.") | |
| print("="*50) | |
| # 1. Confirmation for Preview Scan | |
| confirmation = input("Do you want to proceed with the preview scan? (Y/N): ") | |
| if confirmation.lower() not in ['y', 'yes']: | |
| print("Operation cancelled by the user. Exiting script.") | |
| sys.exit() | |
| print("\nStarting preview scan...") | |
| # Run in preview mode (perform_rename=False) | |
| rename_items(current_dir, perform_rename=False) | |
| # 2. Confirmation for Actual Renaming | |
| print("\n" + "="*50) | |
| print("Ready to perform actual changes based on the preview above.") | |
| confirmation_final = input("Are you sure you want to rename the items? (Type 'YES' in all caps to confirm): ") | |
| print("="*50 + "\n") | |
| if confirmation_final == 'YES': | |
| print("Starting file renaming...") | |
| # Run in actual rename mode (perform_rename=True) | |
| rename_items(current_dir, perform_rename=True) | |
| else: | |
| print("Actual renaming cancelled by the user. Exiting script without changes.") | |
| sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment