"""Remove trailing numbers from file names Strips the numbers at the end of file names in a folder and all its subfolders: "logo-design_01.svg" and "logo-design 1.svg" become "logo-design.svg". 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 import re import tkinter as tk from tkinter import filedialog, messagebox def remove_trailing_numbers(): # Hide the main root tkinter window root = tk.Tk() root.withdraw() print("Script started. Follow the popups...") while True: # Open folder selection dialog folder_path = filedialog.askdirectory(title="Select Folder to Rename Files") # If user cancels or closes the dialog, exit the loop if not folder_path: print("No folder selected. Exiting script.") break renamed_count = 0 # 1. Use os.walk with topdown=False to safely recurse into all subfolders for dirpath, dirnames, filenames in os.walk(folder_path, topdown=False): # 2. Iterate through files in the current subfolder for filename in filenames: file_path = os.path.join(dirpath, filename) name, ext = os.path.splitext(filename) # Regex to match ALL trailing numbers (\d+) and preceding spaces/dashes/underscores new_name = re.sub(r'[\s\-_]*\d+$', '', name) # A name made only of numbers ("2024.jpg") would end up empty, so leave it if not new_name: print(f"Skipped: '{filename}' has no name left without its numbers.") continue # If a new name is generated, rename the file if new_name != name: new_filename = new_name + ext new_file_path = os.path.join(dirpath, new_filename) # Handle potential duplicate destination filenames if os.path.exists(new_file_path): print(f"Skipped: '{new_file_path}' already exists.") continue os.rename(file_path, new_file_path) renamed_count += 1 # Explicit confirmation prompt asking if you want to keep going keep_going = messagebox.askyesno( "Process Complete", f"Renamed {renamed_count} files across this folder and its subfolders.\n\nDo you have more folders to process?" ) # If the user clicks 'No', break the loop and end the script if not keep_going: print("Finished processing. Exiting script.") break if __name__ == "__main__": remove_trailing_numbers()