Contents
- Introduction
- Example 1: Replace string in File
- Example 2: Replace string in the same File
- Summary
To replace a string in File using Python, follow these steps:
- Open input file in read mode and handle it in text mode.
- Open output file in write mode and handle it in text mode.
- For each line read from input file, replace the string and write to output file.
- Close both input and output files.
Example 1: Replace string in File
In
the following example, we will replace the string pyton
with python
in data.txt
file, and write the result to out.txt
.
Python Program
#input file
fin = open["data.txt", "rt"]
#output file to write the result to
fout = open["out.txt", "wt"]
#for each line in the input file
for line in fin:
#read replace the string and write to output file
fout.write[line.replace['pyton', 'python']]
#close input and output files
fin.close[]
fout.close[]
What have we done here?
- Open
data.txt
in read textrt
mode and get the reference tofin
. - Open
out.txt
in write textwt
mode and get the reference tofout
. for line in fin
:for each line infin
i.e.,data.txt
,line.replace[]
: replaces stringpyton
withpython
andfout.write
: writes toout.txt
.fin.close[]
: closes the file referenced byfin
,fout.close[]
: closes the file referenced byfout
.
Input File
Welcome to www.pytonexamples.org. Here, you will find pyton programs for all general use cases.
Output File
Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.
The string pyton
in the file is replaced with the string python
.
Example 2: Replace string in the same File
In the following example, we will replace the string pyton with python in data.txt file, and overwrite the data.txt file with the replaced text.
Python Prgoram
#read input file
fin = open["data.txt", "rt"]
#read file contents to string
data = fin.read[]
#replace all occurrences of the required string
data = data.replace['pyton', 'python']
#close the input file
fin.close[]
#open the input file in write mode
fin = open["data.txt", "wt"]
#overrite the input file with the resulting data
fin.write[data]
#close the file
fin.close[]
What have we done here?
- Open file
data.txt
in read text modert
. fin.read[]
reads whole text indata.txt
to the variabledata
.data.replace[]
replaces all the occurrences ofpyton
withpython
in the whole text.fin.close[]
closes the input filedata.txt
.- In the last three lines, we are opening
data.txt
in write textwt
mode and writing the data todata.txt
in replace mode. Finally closing the filedata.txt
.
Input File
Welcome to www.pytonexamples.org. Here, you will find pyton programs for all general use cases.
The same input file after program execution.
Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.
Summary
In this tutorial of Python Examples, we learned to replace a string with other in file, with help of well detailed examples.
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
s
=
input
[
"Enter text to replace the existing contents:"
]
f
=
open
[
"file.txt"
,
"r+"
]
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
x
=
input
[
"enter text to be replaced:"
]
y
=
input
[
"enter text that will replace:"
]
f
=
open
[
"file.txt"
,
"r+"
]
l
=
f.readlines[]
c
=
0
for
i
in
l:
if
x
in
i:
Replacement
=
i.replace[x, y]
l
=
Replacement
c
+
=
1
f.truncate[
0
]
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
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