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.
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.
- fileinput.input() in Python
- fileinput.filename() in Python
- fileinput.lineno() in Python
- fileinput.filelineno() in Python
- fileinput.isfirstline() in Python
- PyQt5 QSpinBox - Editing Finished Signal
- PyQt5 QDoubleSpinBox - Getting Editing Finished Signal
- Inplace Operators in Python | Set 1 (iadd(), isub(), iconcat()...)
- Inplace Operators in Python | Set 2 (ixor(), iand(), ipow(),…)
- Inplace vs Standard Operators in Python
- Python | Create video using multiple images using OpenCV
- Python | Create a stopwatch using clock object in kivy using .kv file
- Image resizing using Seam carving using OpenCV in Python
- Python | Visualizing O(n) using Python
- Python - Read blob object in python using wand library
- Creating and updating PowerPoint Presentations in Python using python - pptx
- Circular (Oval like) button using canvas in kivy (using .kv file)
- Send mail from your Gmail account using Python
- Cartooning an Image using OpenCV - Python
- Using Iterations in Python Effectively
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.