Python: Inplace Editing using FileInput
Last Updated :
19 Feb, 2020
Python3’s fileinput
provides many useful features that can be used to do many things without lots of code. It comes handy in many places but in this article, we’ll use the fileinput to do in-place editing in a text file. Basically we’ll be changing the text in a text file without creating any other file or overheads.
Syntax:
FileInput(filename, inplace=True, backup='.bak')
Note: The backup is extension for the backup file created before editing.
Example 1:Changing only the first line of file
Text file:
import fileinput
filename = "GFG.txt"
with fileinput.FileInput(filename,
inplace = True , backup = '.bak' ) as f:
for line in f:
if f.isfirstline():
print ( "changing only first line" , end = '\n' )
else :
print (line, end = '')
|
Output:
Example 2:Search and replace line with other line in file
Text file:
import fileinput
filename = "GFG.txt"
with fileinput.FileInput(filename,
inplace = True , backup = '.bak' ) as f:
for line in f:
if "search this line and change it\n" = = line:
print ( "changing the matched line with this line" ,
end = '\n' )
else :
print (line, end = '')
|
Output:
Example 3:Search text inline and replace that line with another line in the file.
Text file:
import fileinput
filename = "GFG.txt"
with fileinput.FileInput(filename,
inplace = True , backup = '.bak' ) as f:
for line in f:
if "searchtext" in line:
print ( "changing this line with line that contains searched text" ,
end = '\n' )
else :
print (line, end = '')
|
Output:
Example 4:Search text and replace that text in file.
Text file:
import fileinput
filename = "GFG.txt"
with fileinput.FileInput(filename,
inplace = True , backup = '.bak' ) as f:
for line in f:
if "replace text" in line:
print (line.replace( "replace text" ,
"changed text" ), end = '')
else :
print (line, end = '')
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...