Here's the updated Python script with a preview and confirmation system:
#!/usr/bin/env python3
import os
import sys
def get_fancy_to_standard_mapping():
"""Return mapping of fancy characters to standard ones"""
return {
# Fancy apostrophes/quotes to standard apostrophe
''': "'",
''': "'",
'"': "'",
'"': "'",
'`': "'",
'´': "'",
# Fancy dashes to standard dash
'–': "-", # en dash
'—': "-", # em dash
'−': "-", # minus sign
'‒': "-", # figure dash
'‑': "-", # non-breaking hyphen
}
def needs_renaming(name, char_map):
"""Check if name contains any fancy characters that need replacement"""
return any(fancy_char in name for fancy_char in char_map.keys())
def clean_name(name, char_map):
"""Replace fancy characters with standard ones"""
cleaned = name
for fancy_char, standard_char in char_map.items():
cleaned = cleaned.replace(fancy_char, standard_char)
return cleaned
def collect_directories_to_rename(root_path, char_map):
"""Collect all directories that need renaming"""
directories_to_rename = []
for dirpath, dirnames, filenames in os.walk(root_path, topdown=False):
for dirname in dirnames:
if needs_renaming(dirname, char_map):
full_path = os.path.join(dirpath, dirname)
new_name = clean_name(dirname, char_map)
new_path = os.path.join(dirpath, new_name)
depth = full_path.count(os.sep)
directories_to_rename.append((depth, full_path, new_path, dirname, new_name))
# Sort by depth (deepest first) to avoid path issues
directories_to_rename.sort(reverse=True)
return directories_to_rename
def collect_files_to_rename(root_path, char_map):
"""Collect all files that need renaming"""
files_to_rename = []
for dirpath, dirnames, filenames in os.walk(root_path):
for filename in filenames:
if needs_renaming(filename, char_map):
old_path = os.path.join(dirpath, filename)
new_name = clean_name(filename, char_map)
new_path = os.path.join(dirpath, new_name)
files_to_rename.append((old_path, new_path, filename, new_name))
return files_to_rename
def display_changes(directories, files):
"""Display all proposed changes"""
total_changes = len(directories) + len(files)
if total_changes == 0:
print("No files or directories found that need renaming.")
return False
print(f"Found {total_changes} items that need renaming:")
print("=" * 60)
if directories:
print(f"\nDIRECTORIES ({len(directories)} items):")
print("-" * 40)
for _, old_path, new_path, old_name, new_name in directories:
print(f" {old_path}")
print(f" → {new_path}")
print(f" ('{old_name}' → '{new_name}')")
print()
if files:
print(f"\nFILES ({len(files)} items):")
print("-" * 40)
for old_path, new_path, old_name, new_name in files:
print(f" {old_path}")
print(f" → {new_path}")
print(f" ('{old_name}' → '{new_name}')")
print()
return True
def get_user_confirmation():
"""Get user confirmation to proceed"""
while True:
response = input("Do you want to proceed with these changes? (y/n/q): ").lower().strip()
if response in ['y', 'yes']:
return True
elif response in ['n', 'no', 'q', 'quit']:
return False
else:
print("Please enter 'y' for yes, 'n' for no, or 'q' to quit.")
def execute_directory_renames(directories):
"""Execute directory renames"""
renamed_count = 0
print("\nRenaming directories...")
for _, old_path, new_path, old_name, new_name in directories:
try:
os.rename(old_path, new_path)
print(f"✓ Renamed: {old_path} → {new_path}")
renamed_count += 1
except OSError as e:
print(f"✗ Error renaming {old_path}: {e}", file=sys.stderr)
return renamed_count
def execute_file_renames(files):
"""Execute file renames"""
renamed_count = 0
print("\nRenaming files...")
for old_path, new_path, old_name, new_name in files:
try:
os.rename(old_path, new_path)
print(f"✓ Renamed: {old_path} → {new_path}")
renamed_count += 1
except OSError as e:
print(f"✗ Error renaming {old_path}: {e}", file=sys.stderr)
return renamed_count
def main():
# Start from current directory
root_path = "."
char_map = get_fancy_to_standard_mapping()
print("Fancy Character Cleanup Tool")
print("=" * 30)
print(f"Scanning directory: {os.path.abspath(root_path)}")
print("Looking for fancy apostrophes and dashes to replace...")
print()
# Collect all changes
print("Scanning for items to rename...")
directories = collect_directories_to_rename(root_path, char_map)
files = collect_files_to_rename(root_path, char_map)
# Display proposed changes
has_changes = display_changes(directories, files)
if not has_changes:
return
# Get user confirmation
if not get_user_confirmation():
print("Operation cancelled.")
return
# Execute changes
print("\nExecuting changes...")
dir_count = execute_directory_renames(directories)
file_count = execute_file_renames(files)
print(f"\nComplete!")
print(f"Directories renamed: {dir_count}/{len(directories)}")
print(f"Files renamed: {file_count}/{len(files)}")
print(f"Total items renamed: {dir_count + file_count}")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nOperation cancelled by user.")
sys.exit(1)