python program to do inplace replace of string in a file

In this tutorial, we will learn how to do inplace replacement of strings in a file in Python. We can always read one file line by line, replace one specific string in the lines and write down that line to a different file. But we will do inplace replacement in a file i.e. we will modify the same file.

This example will show you how to work on a text file, but you can use the same program to any other type of files as well.

fileinput module:

fileinput module provides a couple of useful methods for file related operations. In this tutorial, we are using the below method :

fileinput.FileInput(files=None, inplace=False, backup='', *, mode='r', openhook=None)

We are mainly using the first three parameters. If we pass inplace as True, it will do inplace replacement of file content. The backup takes one format of the backup file. This file is used to backup the content.

Python program:

Below program does inplace replacement of a string in a file.

import fileinput

file_path = 'content.txt'

with fileinput.FileInput(file_path, inplace=True, backup='.bak') as f:
    for line in f:
        if 'Hello' in line:
            new_line = line.replace('Hello', 'HELLO')
            print(new_line, end='')
        else:
            print(line, end='')

If the file content.txt contains the below text :

Hello World !!
Hello Everyone !!

It will change it to:

HELLO World !!
HELLO Everyone !!

The backup, i.e. the original content will be saved in a content.txt.bak file in the same folder.