Python: Inplace Editing using FileInput
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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
Example 2:Search and replace line with other line in file
Example 3:Search text inline and replace that line with another line in the file.
Example 4:Search text and replace that text in file.