How To Search And Replace Text In A File Using Python

In this article, we will show you 3 ways you can search and replace text in a file. To replace text in a file, it requires filtering the specified text then overwriting that specified text with a new text.

For example, replacing the word “Sarah” in the sentence “My name is Sarah” with “John”, results in “My name is John”.

This is the following text file we will be using, it contains a few short sentences with the individual named “Sarah” we will be changing this name to “John”.

Method 1: Using open() function

Python’s open function is used to open internally stored files, this means it can open text files and edit text files.

To search and replace text we need to use the open function to read our file then search and replace the specified text with its “write” attribute.

These are the following parameters of our open() function:

  • file: Location of our file
  • Mode: The action we need on the file, this can be either “r” to read the file, or “w” to write on the file

Replacing and copying data to a new text file

# create our variables 
word = "Sarah"
replacement = "John"
text_file = 'textfile.txt'

#Opening our text file
with open(text_file, "r") as file:
  
    # Reading our text file
    file_data = file.read()
  
    # Searching and replacing the text
    # using the replace() function
    file_data_replaced = file_data.replace(word, replacement)
    
#Opening a new text file as write
with open('new_text.txt', 'w') as file:
  
    # Writing the replaced data in our new text file
    file.write(file_data_replaced)

In this method, we first declared the variables which contained our keywords and the location of our text file.

Next, we opened and read the text file using the function read(), and replaced the keywords using replace(word, replacement). This data was then copied to our new text file.

It should be noted that this method does not write over the original file, rather it copies the new data to a separate file.

Overwriting current text file

To overwrite our current text file, the process is pretty much the same. Except at the last step where we need to write on our current text file “text_file.txt” instead of a different text file.

By doing so python copies the data with the replaced text and overrides our current text file.

# Read the file
with open(text_file, 'r') as file:
    
  file_data = file.read()

# Replace the our key word
updated_file_data = file_data.replace(word, replacement)

# Write the file and replace the words in the file
with open(text_file, 'w') as file:
  file.write(updated_file_data)

Method 2: Using fileinput Module

A library we can use is fileinput which is a library that allows us to get a text file as input and append the data in the file by using its function fileinput.input().

These are the following parameters of our fileinput.input() function:

  • files: Location of our file
  • inplace: True/False, basically setting this option to True parse our text file line by line, and edit a line in-place while going through the lines
import fileinput #import our library

#iterate over each line of our text file and replacing Sarah with John
with fileinput.FileInput(text_file, inplace=True) as file:
    for line in file:
        print(line.replace(word, replacement))

Basically what this function does is it iterates each line and replaces the values it detects or keyword Sarah with replacement John, and since the attribute inplace is set to True. Once the code parses over the line, it replaces the text during the parse.

Method 3: Using pathlib2

Another package we can use is pathlib2, which helps with manipulating new paths from names of files and, checking for various properties of paths, and creating files and folders at specific paths. This means we can use it to manipulate data within our text file.

The exact function we will be using is the Path() function, this function helps detect and find our specified folder.

These are the following parameters of our Path() function:

  • file: Location of our file
!pip install pathlib2 #install pathlib2
from pathlib2 import Path #import our package

#importing our text file
file = Path(text_file)

#reading our text file
text = file.read_text()

#replace our specified word with our replacement word
updated_text = text.replace(word, replacement)

#write updated text to our file. 
file.write_text(updated_text)

In this method the only difference is that we imported a new function called “Path()” this function helps detect our text file. After the file is read we just replaced our specified keyword and rewrite the file using “file.write_text(updated_text)”.