Open In App

How to Search and Replace Text in a file in Python

Last Updated : 21 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we’ll explore four effective methods to search and replace text within a file using Python. These methods range from basic built-in functions to powerful modules like re and fileinput.

Method 1: Using Basic File Handling (open() and replace())

Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents:

To replace text in a file we are going to open the file in read-only using the open() function. Then we will read and replace the content in the text file using the read() and replace() functions.

Syntax:

open(file, mode='r')

Parameters:

  • file: Location of the file
  • mode: Mode in which you want toopen the file.

Example:

Python
search_text = "dummy"
replace_text = "replaced"

with open('SampleFile.txt', 'r') as file:
    data = file.read()
    data = data.replace(search_text, replace_text)

with open('SampleFile.txt', 'w') as file:
    file.write(data)

print("Text replaced")

Output:

Text replaced

Explanation:

  • Reads the entire file into memory using read().
  • Replaces all occurrences using replace().
  • Overwrites the file with updated content.

Note: This method is not suitable for large files due to memory usage.

Method 2: Using pathlib2 (Object-Oriented Approach)

pathlib2 provides an elegant, OOP-style interface for file operations. This method is cleaner and often preferred in structured scripts.

We are required to first install pathlib2 module, install it using the following command:

pip install pathlib2

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. To replace the text using pathlib2 module we will use the Path method of pathlib2 module.

Syntax:

from pathlib2 import Path

Path(file_path).read_text()

Path(file_path).write_text(data)

Parameters:

  • file_path: Location of the file you want to open

Example:

Python
from pathlib2 import Path

def replacetext(search_text, replace_text):
    file = Path("SampleFile.txt")
    data = file.read_text()
    data = data.replace(search_text, replace_text)
    file.write_text(data)
    return "Text replaced"

print(replacetext("dummy", "replaced"))

Output:

Text replaced

Explanation:

  • read_text() and write_text() simplify reading and writing file contents.
  • No need for explicit open/close statements.
  • Clean and readable, especially for beginners and small projects.

Method 3: Using re Module (Regex-based Search and Replace)

This method is ideal when you need pattern matching — for example, replacing all digits, special formats, or variations of a word.

Syntax:

re.sub(pattern, repl, string, count=0)

Parameters:

  • repl : Text you want to add
  • string : Text you want to replace

Example:

Python
import re

def replacetext(search_text, replace_text):
    with open('SampleFile.txt', 'r+') as f:
        file_data = f.read()
        file_data = re.sub(search_text, replace_text, file_data)
        f.seek(0)
        f.write(file_data)
        f.truncate()

    return "Text replaced"

print(replacetext("dummy", "replaced"))

Output:

Text replaced

Method 4: Using fileinput Module (In-place Editing with Backup)

fileinput is a powerful tool for line-by-line replacement and supports in-place editing with optional backup creation.

Syntax:

FileInput(files, inplace=False, backup='', mode='r')

Parameters:

  • files: Location of the text file
  • mode: Mode in which you want toopen the file
  • inplace: If value is True then the file is moved to a backup file and
  • backup: Extension for the backup file

Explanation:

Python
from fileinput import FileInput

def replacetext(search_text, replace_text):
    with FileInput("SampleFile.txt", inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(search_text, replace_text), end='')
    return "Text replaced"

print(replacetext("dummy", "replaced"))

Output:

Text replaced

Related Articles:


Next Article
Practice Tags :

Similar Reads