"""Find and replace in file and folder names Replaces a character or piece of text in the names of all files and folders inside a folder, including subfolders: replace "_" with "-", remove "copy", and so on. Free script from LinearAndLoom Icons: https://linearandloomicons.netlify.app/scripts/ Provided as is. Renaming and zipping cannot be undone, so try it on a copy of your folder first. """ import os from tkinter import Tk, filedialog def batch_rename(): # Hide the main Tkinter window root = Tk() root.withdraw() root.attributes('-topmost', True) # Bring the dialog to the front # 1. Ask for the target folder print("Opening folder selection window...") target_folder = filedialog.askdirectory(title="Select Target Folder") if not target_folder: print("No folder selected. Exiting script.") return print(f"Selected Folder: {target_folder}\n") # 2. Get the strings to find and replace old_str = input("Enter the character/string to FIND: ") if not old_str: print("Search string cannot be empty. Exiting script.") return new_str = input("Enter the character/string to REPLACE WITH: ") print("\nStarting renaming process...\n") rename_count = 0 # 3. Iterate over all files and folders (Bottom-Up) # topdown=False is critical so we rename files inside a folder # before renaming the parent folder itself. for dirpath, dirnames, filenames in os.walk(target_folder, topdown=False): # Rename files first for filename in filenames: if old_str in filename: old_file_path = os.path.join(dirpath, filename) new_filename = filename.replace(old_str, new_str) new_file_path = os.path.join(dirpath, new_filename) # Never overwrite another file, and never leave a file without a name if not new_filename or os.path.exists(new_file_path): print(f"[File] Skipped: {filename} ('{new_filename}' already exists or is empty)") continue os.rename(old_file_path, new_file_path) print(f"[File] Renamed: {filename} -> {new_filename}") rename_count += 1 # Rename folders next for dirname in dirnames: if old_str in dirname: old_dir_path = os.path.join(dirpath, dirname) new_dirname = dirname.replace(old_str, new_str) new_dir_path = os.path.join(dirpath, new_dirname) if not new_dirname or os.path.exists(new_dir_path): print(f"[Folder] Skipped: {dirname} ('{new_dirname}' already exists or is empty)") continue os.rename(old_dir_path, new_dir_path) print(f"[Folder] Renamed: {dirname} -> {new_dirname}") rename_count += 1 print(f"\nDone! Successfully renamed {rename_count} item(s).") if __name__ == "__main__": batch_rename()