Open In App

Replace Multiple Lines From A File Using Python

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, replacing multiple lines in a file consists of updating specific contents within a text file. This can be done using various modules and their associated functions. In this article, we will explore three different approaches along with the practical implementation of each approach in terms of example code and output.

Replace Multiple Lines From A File Using Python

Below are the possible approaches to replace multiple lines from a file using Python:

  • Using fileinput module
  • Using re module
  • Using tempfile and shutil modules

input.txt:

Geeks for Geeks
Python is awesome
Geeks for coding practice
Geeks for learning algorithms
Geeks for interviews

Replace Multiple Lines From A File Using fileinput module

In this approach, the fileinput module is used to replace multiple lines in a file. The function approach1Fn() takes a filename, a list of old lines, and a corresponding list of new lines. It iterates through the file using fileinput. FileInput in inplace mode, replacing occurrences of old lines with new lines. The modified lines are stored in the ‘res‘ list, printed to the console, and written back to the input file.

Python3




import fileinput
 
def approach1Fn(filename, old_lines, new_lines):
    res = []
    with fileinput.FileInput(filename, inplace=True,) as file:
        for line in file:
            for old, new in zip(old_lines, new_lines):
                line = line.replace(old, new)
            res.append(line)
            print(line, end='')
 
    return res
 
old_lines = ["Geeks for Geeks", "Python is awesome"]
new_lines = ["GFG", "Python is amazing"]
res = approach1Fn('input.txt', old_lines, new_lines)
for line in res:
    print(line, end='')
with open('input.txt', 'w') as file:
    for line in res:
        file.write(line)


Output:

GFG
Python is amazing
Geeks for coding practice
Geeks for learning algorithms
Geeks for interviews

Replace Multiple Lines From A File Using re module

In this approach, we use the re module to replace multiple lines in a file. The re.sub function is used to perform case-sensitive string substitution, where each occurrence of the specified old lines is replaced with the corresponding new lines. The updated content is then written back to the same file, and the modified lines are printed to the console for verification.

Python3




import re
 
def approach2Fn(filename, old_lines, new_lines):
    with open(filename, 'r') as file:
        data = file.read()
    for old, new in zip(old_lines, new_lines):
        data = re.sub(re.escape(old), new, data)
    with open(filename, 'w') as file:
        file.write(data)
    res = data.split('\n')
    for line in res:
        print(line)
 
old_lines = ["Geeks for Geeks", "Python is awesome"]
new_lines = ["GFG", "Python is amazing"]
approach2Fn('input.txt', old_lines, new_lines)


Output:

GFG
Python is amazing
Geeks for coding practice
Geeks for learning algorithms
Geeks for interviews

Replace Multiple Lines From A File Using tempfile and shutil modules

In this approach, we are using the tempfile and shutil modules to replace multiple lines in a file. The function approach2Fn() reads each line from the input file, replaces specified old lines with new lines, and writes the updated content to a temporary file. Afterward, the temporary file is moved to replace the original file. The function returns a list of updated lines, which are then printed to the console and written back to the input file.

Python3




import tempfile
import shutil
 
 
def approach2Fn(filename, old_lines, new_lines):
    updated_lines = []
    temp_file = tempfile.NamedTemporaryFile(delete=False)
 
    with open(filename, 'r') as file:
        for line_number, line in enumerate(file, start=1):
            for old, new in zip(old_lines, new_lines):
                line = line.replace(old, new)
            temp_file.write(line.encode())
            updated_lines.append(line.strip())
    temp_file.close()
    shutil.move(temp_file.name, filename)
    return updated_lines
 
 
old_lines = ["Geeks for Geeks", "Python is awesome"]
new_lines = ["GFG", "Python is amazing"]
res = approach2Fn('input.txt', old_lines, new_lines)
for line in res:
    print(line)
with open('input.txt', 'w') as file:
    for line in res:
        file.write(line + '\n')


Output:

GFG
Python is amazing
Geeks for coding practice
Geeks for learning algorithms
Geeks for interviews


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads