The Wayback Machine - https://web.archive.org/web/20240717024405/https://www.geeksforgeeks.org/python-program-to-replace-text-in-a-file/
Open In App

Python Program to Replace Text in a File

Last Updated : 30 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 all the text stored in the text file, for this, we will open the file in reading and writing mode and it will rewrite all the text.

Python3




# Python program to replace text in a file
s = input("Enter text to replace the existing contents:")
f = open("file.txt", "r+")
 
# file.txt is an example here,
# it should be replaced with the file name
# r+ mode opens the file in read and write mode
f.truncate(0)
f.write(s)
f.close()
print("Text successfully replaced")


Output: 

Enter text to replace the existing contents: Geeks
Text successfully replaced

Method 2: Using Replace function in for loop

The simple for loop is a conventional way to traverse through every line in the given text file and find the line we want to replace. Then, the desired line can be replaced by using the replace() function.  Finally, the file is opened in the write mode, and the replaced content is written in the given file.

Python3




# Python program to replace text in a file
x = input("enter text to be replaced:")
y = input("enter text that will replace:")
 
# file.txt should be replaced with
# the actual text file name
f = open("file.txt", "r+")
 
# each sentence becomes an element in the list l
l = f.readlines()
 
# acts as a counter to know the
# index of the element to be replaced
c = 0
for i in l:
    if x in i:
 
        # Replacement carries the value
        # of the text to be replaced
        Replacement = i.replace(x, y)
 
        # changes are made in the list
        l = Replacement
    c += 1
 
# The pre existing text in the file is erased
f.truncate(0)
 
# the modified list is written into
# the file thereby replacing the old text
f.writelines(l)
f.close()
print("Text successfully replaced")


Output:

Enter text to be replaced: Geeks
Enter text that will replace: Geekforgeeks
Text successfully replaced

Method 3: Using the OS module to replace the file with new text

We use the os module to rename a new file with the original file name. In this method instead of editing the already existing file, we instead create a new file with the modified content and then delete the old file and rename the new file.

Python




# Program to replace text in a file
import os
x = input("Enter text that will replace the existing text:")
f = open("file.txt", "r+")
f1 = open("new.txt", "r+")
 
f1.write(x)
os.remove("file.txt")
os.rename("new.txt", "file.txt")
f1.close()
 
print("File replaced")


Output:

Enter text that will replace the existing text: geeks
File replaced

Method 4: Using fileinput.input()

The fileinput.input() method gets the file as the input line by line and is mainly utilized for appending and updating the data in the given file. The fileinput and sys module need to be imported to the current Python code in order to run the code without any errors. The following code uses the fileinput.input() function for replacing the text in a line in Python.

Python3




import sys
import fileinput
 
x = input("Enter text to be replaced:")
y = input("Enter replacement text")
 
for l in fileinput.input(files = "file.txt"):
    l = l.replace(x, y)
    sys.stdout.write(l)


Output:

Enter text to be replaced: Geeks
Enter replacement text: Geeksforgeeks


Previous Article
Next Article

Similar Reads

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
How to search and replace text in a file in Python ?
In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing text without using any external module Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents: To r
5 min read
Replace Commas with New Lines in a Text File Using Python
Replacing a comma with a new line in a text file consists of traversing through the file's content and substituting each comma with a newline character. In this article, we will explore three different approaches to replacing a comma with a new line in a text file. Replace Comma With a New Line in a Text FileBelow are the possible approaches to rep
2 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
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 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 that, we open the file in write-only mode and write
2 min read
Python - Find text using beautifulSoup then replace in original soup variable
Python provides a library called BeautifulSoup to easily allow web scraping. BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a w
3 min read
Python program to extract Email-id from URL text file
Prerequisite : Pattern Matching with Python Regex Given the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work. Example : Input : Hello This is Geeksforgeeks review-team@geeksforgeeks.org review-team@geeksforgeeks.org GfG is a portal for gee
1 min read
Python program to Count the Number of occurrences of a key-value pair in a text file
Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file with Python Program to Count the occurrences of a key-value pairNaive Approach to Count the Occurrences of a key-value PairUsing Python built-in collections.CounterUsing regular expressions (re module)Text file: Naive Approach to
3 min read
Python Program to Count Words in Text File
In this article, we are going to see how to count words in Text Files using Python. Example 1: Count String Words First, we create a text file of which we want to count the number of words. Let this file be SampleFile.txt with the following contents: File for demonstration:Below is the implementation: C/C++ Code # creating variable to store the # n
3 min read
Practice Tags :
three90RightbarBannerImg