Search and Replace Text in a File Using Python



File manipulation is a fundamental aspect of programming, especially when dealing with data processing and management. Python offers powerful tools for handling files and text efficiently.

A common task is searching for specific text patterns within a file and replacing them with desired content. This article explores several practical methods for searching and replacing text in a file using Python.

Basic Text Replacement

Let's start with a simple example of searching for a specific word in a file and replacing it with another word. In this particular example, we'll search for the word "old" and replace it with "new" ?

Example

In the following example, the search_and_replace function takes the file path, the word to search for, and the replacement word as input. It opens the file in read mode ('r') and reads the entire content into the file_contents variable.

The replace() method is then used to substitute all occurrences of the search_word with the replace_word. Finally, the file is opened in write mode ('w'), and the updated content is written back to the file.

def search_and_replace(file_path, search_word, replace_word):
def search_and_replace(file_path, search_word, replace_word):  
    try:  
        with open(file_path, 'r') as file:  
            file_contents = file.read()  

        updated_contents = file_contents.replace(search_word, replace_word)  

        with open(file_path, 'w') as file:  
            file.write(updated_contents)  
        print("Text replacement completed successfully.")  
    except FileNotFoundError:  
        print(f"Error: The file '{file_path}' was not found.")  
    except Exception as e:  
        print(f"An error occurred: {e}")  

file_path = 'example.txt'  
search_word = 'old'  
replace_word = 'new'  

# Create a dummy file for the example  
with open(file_path, 'w') as f:  
    f.write("This is an old house. An old car is parked there.")  
search_and_replace(file_path, search_word, replace_word)  

Following is the output of the above code ?

Text replacement completed successfully.  

example.txt Before:

This is an old house. An old car is parked there.  

example.txt After:

This is a new house. A new car is parked there.  

Case-Insensitive Text Replacement

In some cases, we may need to perform a case-insensitive search and replace operation. To achieve this, we can use regular expressions with the re module in Python.

Example

The function case_insensitive_search_and_replace() takes a file path, search word, and replace word. It opens the file, reads its contents, and uses a case-insensitive regular expression to replace all occurrences of the search word with the replace word. Finally, it overwrites the file with the modified content.

import re

def case_insensitive_search_and_replace(file_path, search_word, replace_word):
   with open(file_path, 'r') as file:
      file_contents = file.read()

      pattern = re.compile(re.escape(search_word), re.IGNORECASE)
      updated_contents = pattern.sub(replace_word, file_contents)

   with open(file_path, 'w') as file:
      file.write(updated_contents)

# Example usage
file_path = 'example.txt'
search_word = 'old'
replace_word = 'new'
case_insensitive_search_and_replace(file_path, search_word, replace_word)

Following is the output of the above code ?

This is an new file. It has some new content. And some new stuff. This is the end.

Regular Expression Search and Replace

Regular expressions offer a robust and flexible way to search and replace text in a file. We can use patterns to match complex text patterns and perform sophisticated replacements. Let's see an example of using regular expressions for search and replace ?

Example

The regex_search_and_replace function takes a file path, search pattern, and replace pattern. It reads the file content, then uses re.sub() with the given patterns to find and replace text. Specifically, r'\b(\d+)\b' finds numbers. r'[\1]' replaces them with bracketed versions. Finally, it overwrites the file with the modified content.

import re
def regex_search_and_replace(file_path, search_pattern, replace_pattern):
   with open(file_path, 'r') as file:
      file_contents = file.read()

      updated_contents = re.sub(search_pattern, replace_pattern, file_contents)

   with open(file_path, 'w') as file:
      file.write(updated_contents)

file_path = 'example.txt'
search_pattern = r'\b(\d+)\b'
replace_pattern = r'[\1]'
regex_search_and_replace(file_path, search_pattern, replace_pattern)

Following is the output of the above code ?

This is a test file with some numbers like [123], [45], and [6].

Search and Replace with Context Preservation

Sometimes, we may need to preserve the context around the search term when performing the replacement. For instance, we may want to replace the word "old" with "new" while keeping the original capitalization. Let's see how to achieve this ?

Example

In the following example, the function 'preserve_context_search_and_replace' takes a file path, search word, and replace word. It reads the file, creates a case-insensitive regex pattern for the search word, and uses re.sub() with a lambda function to replace matches while preserving capitalization. Finally, it writes the updated content back to the file.

import re

def preserve_context_search_and_replace(file_path, search_word, replace_word):
   with open(file_path, 'r') as file:
      file_contents = file.read()

      pattern = re.compile(rf'\b{re.escape(search_word)}\b', re.IGNORECASE)
      updated_contents = pattern.sub(lambda match: match.group().replace(search_word, replace_word), file_contents)

   with open(file_path, 'w') as file:
      file.write(updated_contents)

#Example usage

file_path = 'example.txt'
search_word = 'old'
replace_word = 'new'
preserve_context_search_and_replace(file_path, search_word, replace_word)

Following is the output of the above code ?

This is an old file.  
It contains OLD data.  
The word "old" is repeated.  
This is not so old.  
This is an older file. 
Updated on: 2025-03-05T17:39:07+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements