Saturday, July 25, 2026
HomeLanguagesPython Program to Replace Specific Line in File

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 that, we open the file in write-only mode and write the modified data using writelines().

File for demonstration:

Explanation:

First, open the File in read-only mode and read the file line by line using readlines() method, and store it in a variable.

with open('example.txt','r',encoding='utf-8') as file:
    data = file.readlines()

The variable will contain a list of lines, Printing it will show all the lines present inside the list.

print(data)

Make necessary changes to a specific line. (Here, I have modified the second line)

data[1] = "Here is my modified Line 2\n"

Open the file again in write-only mode and write the modified data using writelines() method.

With open('example.txt', 'w', encoding='utf-8') as file:
    file.writelines(data)

Below is the implementation:

Python3




with open('example.txt', 'r', encoding='utf-8') as file:
    data = file.readlines()
  
print(data)
data[1] = "Here is my modified Line 2\n"
  
with open('example.txt', 'w', encoding='utf-8') as file:
    file.writelines(data)


Output:

['Line 1\n', 'Here is my modified Line 2\n', 'Line 3']

After Modification:

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32520 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6903 POSTS0 COMMENTS
Nicole Veronica
12017 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12115 POSTS0 COMMENTS
Shaida Kate Naidoo
7023 POSTS0 COMMENTS
Ted Musemwa
7265 POSTS0 COMMENTS
Thapelo Manthata
6980 POSTS0 COMMENTS
Umr Jansen
6972 POSTS0 COMMENTS