LinearAndLoom Icons

Find and Replace Text in File Names (Free Python Script)

Free Python script to bulk rename files and folders by replacing a character or word in their names, including all subfolders.

Download find-and-replace-in-filenames.pyPython 3 · 79 lines · 3 KB · free

Sometimes a whole set of files needs the same small change: underscores to hyphens, an old brand name to a new one, or the word "copy" removed. This script replaces any piece of text in the names of all files and folders inside a folder.

What it does

Examples:

How to use it

  1. Run the script (see below). A folder window opens.
  2. Choose the folder.
  3. Go back to the terminal window. Type the text to find and press Enter.
  4. Type the replacement and press Enter. Press Enter on its own to remove the text.

Renaming cannot be undone with Ctrl+Z. Run the script on a copy of the folder the first time, until you trust the result.

How to run a Python script

  1. Install Python 3 from python.org if you do not have it. It is free. On Windows, tick Add Python to PATH in the installer.
  2. Download the script with the button on this page and save it somewhere easy, such as your Desktop.
  3. Open a terminal. On Windows, press the Windows key, type cmd and press Enter. On Mac, open Terminal from Applications > Utilities.
  4. Type python followed by a space (on Mac, python3 and a space), drag the script file into the terminal window and press Enter.

On Windows you can also just double-click the script after installing Python.

The folder window is drawn with Tkinter, which comes with Python on Windows and Mac. On Linux, install it with sudo apt install python3-tk.

Good to know

Questions

Can I replace spaces with hyphens?

Yes. When asked what to find, press the space bar once and then Enter. For the replacement, type -.

Can it rename only files and leave folders alone?

Not as written. To do that, open the script in a text editor and delete the block that starts with the comment # Rename folders next.

How do I clean up many different symbols at once?

Use the file name cleaner script. It handles spaces, capitals, accents and symbols in one pass.

The code

This is the complete script. Nothing else is downloaded or installed.

"""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()

Download find-and-replace-in-filenames.pyPython 3 · 79 lines · 3 KB · free

These scripts are free. If one saved you time, you can say thanks by buying a pack from the LinearAndLoom Etsy shop.

More scripts