fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← Python

Python / 4 MIN READ

Python Find and Replace

Python find and replace script

From the original Fervor library. Examples may use older package versions.

Tutorial: Creating a Python Script to Find and Replace Text in a File

Ever wanted to quickly replace a word or phrase in a file with something else? With Python, you can automate this task like a pro! Here’s how you can create a Python script to perform a find and replace operation on a file.


Step 1: Understand the Basics

What the Script Will Do:

  1. Open a file and read its contents.
  2. Search for a specific word or phrase (the find part).
  3. Replace that word or phrase with something else (the replace part).
  4. Save the updated content back to the file or create a new file.

Step 2: Write the Script

Here’s the complete Python script:

# find_replace.py

def find_and_replace(file_path, find_word, replace_word, output_file=None):
    """
    Replace all occurrences of a word in a file and save the updated content.
    
    :param file_path: Path to the input file.
    :param find_word: The word/phrase to find.
    :param replace_word: The word/phrase to replace it with.
    :param output_file: (Optional) Path to save the updated file. If None, overwrites the original file.
    """
    try:
        # Open the file for reading
        with open(file_path, 'r') as file:
            content = file.read()
        
        # Replace occurrences of the word
        updated_content = content.replace(find_word, replace_word)
        
        # Save the updated content
        if output_file:
            with open(output_file, 'w') as file:
                file.write(updated_content)
            print(f"Replaced '{find_word}' with '{replace_word}' and saved to {output_file}")
        else:
            with open(file_path, 'w') as file:
                file.write(updated_content)
            print(f"Replaced '{find_word}' with '{replace_word}' in the original file.")
    
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' does not exist.")
    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage:
# Uncomment the following lines and replace the arguments with your own values to test the script.
# file_path = "example.txt"
# find_word = "old_word"
# replace_word = "new_word"
# find_and_replace(file_path, find_word, replace_word)

Step 3: Save the Script

  1. Copy the script above into a new file.
  2. Save it as find_replace.py.

Step 4: Run the Script

A. Prepare a Sample File

  1. Create a file named example.txt with the following content:
    Hello, world! Python is great. Let's learn Python together.
    
  2. Save it in the same directory as your script.

B. Execute the Script

  1. Open your terminal and navigate to the directory containing the script and file:
    cd path/to/your/script
    
  2. Run the script:
    python3 find_replace.py
    
  3. Replace the sample code with specific inputs:
    file_path = "example.txt"
    find_word = "Python"
    replace_word = "coding"
    find_and_replace(file_path, find_word, replace_word)
    

C. Check the Results

  • Open example.txt and you should see:
    Hello, world! coding is great. Let's learn coding together.
    

Step 5: Advanced Options

Option 1: Save to a New File

To avoid overwriting the original file, provide a path for the output file:

find_and_replace("example.txt", "Python", "coding", "updated_example.txt")

Option 2: Case-Insensitive Replacement

If you want to replace words regardless of case (e.g., Python, PYTHON, python):

import re

def find_and_replace_case_insensitive(file_path, find_word, replace_word, output_file=None):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
        
        # Replace using a regex with case-insensitive flag
        updated_content = re.sub(find_word, replace_word, content, flags=re.IGNORECASE)
        
        if output_file:
            with open(output_file, 'w') as file:
                file.write(updated_content)
            print(f"Replaced '{find_word}' with '{replace_word}' and saved to {output_file}")
        else:
            with open(file_path, 'w') as file:
                file.write(updated_content)
            print(f"Replaced '{find_word}' with '{replace_word}' in the original file.")
    
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' does not exist.")
    except Exception as e:
        print(f"An error occurred: {e}")

Step 6: Make It User-Friendly (Optional)

Add command-line arguments so users can pass file paths and words directly:

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Find and replace text in a file.")
    parser.add_argument("file", help="Path to the input file.")
    parser.add_argument("find", help="Word/phrase to find.")
    parser.add_argument("replace", help="Word/phrase to replace it with.")
    parser.add_argument("--output", help="Path to save the updated file (optional).")

    args = parser.parse_args()
    
    find_and_replace(args.file, args.find, args.replace, args.output)

Run it like this:

python3 find_replace.py example.txt "Python" "coding" --output updated_example.txt

You’re All Set!

Now you’ve got a flexible Python script to find and replace text in files. 🚀 Try customizing it further, like handling multiple files or adding a preview feature.

Keep your curiosity going.Explore more Python →
287 TUTORIALS · 22 TOPICSREADY