Replace Multiple Lines From A File Using Python
Last Updated :
28 Apr, 2025
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
Similar Reads
Remove Multiple Characters from a String in Python Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Letâs explore the different ways to achieve this in det
2 min read
Python - Reading last N lines of a file Prerequisite: Read a file line-by-line in PythonGiven a text file fname, a number N, the task is to read the last N lines of the file.As we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to read last N lines of a file using Python. File:
5 min read
Python - Replace multiple characters at once Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least.Using translate() with maketrans() translate() method combined with maketrans() is the most efficient way to replace mult
2 min read
Python Program to Replace Specific Line in File In this article, we are going to write a Python program to replace specific lines in the file. We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after th
2 min read
Reading .Dat File in Python Python, with its vast ecosystem of libraries and modules, provides a flexible and efficient environment for handling various file formats, including generic .dat files. In this article, we will different approaches to reading and process .dat files in Python. your_file.dat 1.0 2.0 3.04.0 5.0 6.07.0
2 min read
Python Program to Replace Text in a File In this article, we are going to replace Text in a File using Python. Replacing Text could be either erasing the entire content of the file and replacing it with new text or it could mean modifying only specific words or sentences within the existing text.Method 1: Removing all text and write new te
3 min read