Open In App

Python Program to Replace Specific Line in File

Last Updated : 14 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:


Previous Article
Next Article

Similar Reads

Python Program to Delete Specific Line from File
In this article, we are going to see how to delete the specific lines from a file using Python Throughout this program, as an example, we will use a text file named months.txt on which various deletion operations would be performed. Method 1: Deleting a line using a specific position In this method, the text file is read line by line using readline
3 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Method 1: R
7 min read
Python - Replace vowels in a string with a specific character K
Given a string, replace all the vowels with character K. Input : test_str = "Geeks for Geeks"; K='#'Output : "G##ks f#r G##ks" Explanation : All the vowels in test_str are replaced by a given particular character. Input : test_list = "GFG"; K="$"Output : GFGExplanation : As test_str contained no vowel, so the same string is returned. Method #1 : Us
7 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 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 text in the same file In this method we replacing a
3 min read
Python program to Reverse a single line of a text file
Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer science portal User choice = 0 Output: geek a is This
2 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways
3 min read
Retrieve A Specific Element In a Csv File using Python
We have given a file and our task is to retrieve a specific element in a CSV file using Python. In this article, we will see some generally used methods for retrieving a specific element in a CSV file. Retrieve a Specific Element in a CSV File Using PythonBelow are some of the ways by which we can retrieve a specific element in a CSV file using Pyt
2 min read
Practice Tags :