forLoop Along With the
replace()Function to Replace a Line in a File in Python
- Create a New File With the Refreshed Contents and Replace the Original File in Python
fileinput.input()Function for Replacing the Text in a Line in Python
reModule to Replace the Text in a Line in Python
File handling is considered an essential aspect of any web application. Similar to most programming languages, Python is perfectly capable of supporting file handling. It allows you to deal with files of different types, essentially to perform some basic operations like reading and writing. It also provides some other file handling options to operate the files.
This tutorial demonstrates the different methods available to replace a line in a file in Python.
To demonstrate the different ways to replace a line in a file in this article, we will take a text file,
Text file (
There are always second chances in life. Anybody can bounce back from hardships. The hardships that we face are just a test to check our will. A strong will is all it takes to bounce back from a loss.
The path of the storage directory of this file might be different in the reader’s computer; therefore, it is advised to adjust accordingly.
for Loop Along With the
replace() Function to Replace a Line in a File in Python
open() function is utilized to open a file in Python. The file can be opened in either format of text or binary, which depends on the programmer. The
open() function has various modes, and all of them provide different accessibility options to open a file.
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. All of this is done in the
read mode. Finally, the file is opened in the
write mode, and the replaced content is written in the given file.
The following code uses the
for loop along with the
# opening the file in read mode file = open("motivation.txt", "r") replacement = "" # using the for loop for line in file: line = line.strip() changes = line.replace("hardships", "situations") replacement = replacement + changes + "\n" file.close() # opening the file in write mode fout = open("motivation.txt", "w") fout.write(replacement) fout.close()
Create a New File With the Refreshed Contents and Replace the Original File in Python
Several functions are at work to implement this process. The knowledge of the process of all these functions is necessary to execute this method successfully. We need to import several functions from three modules to the Python code.
- Firstly, we need to import the
mkstemp()function from the
tempfilemodule. This function is utilized to return a tuple as an output along with a path and a file descriptor.
- Then, we need to import two functions from the
shutilmodule. The first function is the
copymode()function, which is utilized in copying the permission bits from a source to the destination path. The second function is the
move()function, which allows the movement of files from one place to another.
- Then, we need to import two functions from the
- Finally, we need to import the
remove()function from the
OSmodule. This function allows the deletion of a path.
All these modules need to be imported to the current Python code to run the code without any errors. An example code that implements this way is as follows.
from tempfile import mkstemp from shutil import move, copymode from os import fdopen, remove # storing the path where the file is saved on your device as a variable path="C:\\Users\Admin\Desktop\python\test\motivation.txt" def replacement(filepath, hardships, situations): # Creating a temp file fd, abspath = mkstemp() with fdopen(fd,'w') as file1: with open(filepath,'r') as file0: for line in file0: file1.write(line.replace(hardships,situations)) copymode(filepath, abspath) remove(filepath) move(abspath, filepath) replacement(path,'hardships','situations')
fileinput.input() Function for Replacing the Text in a Line in Python
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.
sys modules 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.
import fileinput import sys def replacement(file, previousw, nextw): for line in fileinput.input(file, inplace=1): line = line.replace(previousw, nextw) sys.stdout.write(line) var1 = "hardships" var2 = "situations" file = "motivation.txt" replacement(file, var1, var2)
re Module to Replace the Text in a Line in Python
re module is a built-in module that Python provides to programmers that deal with Regular Expression, and it needs to be imported to the code. It helps in performing the task of searching for a pattern in a given particular string.
In this method, we use two functions, namely,
re.escape(), from the
RegEx module. The
re.compile() function is utilized to generate a regular expression object from the regular expression pattern, which is then used for matching. The
re.compile() function is utilized to ignore or escape the special characters in Python.
The following code uses several functions from the
Regex module to replace the text in a line in Python.
import re def replacement(Path, text, subs, flags=0): with open(filepath, "r+") as f1: contents = f1.read() pattern = re.compile(re.escape(text), flags) contents = pattern.sub(subs, contents) f1.seek(0) f1.truncate() f1.write(file_contents) filepath="motivation.txt" text="hardships" subs="situations" replacement(filepath, text, subs)
Here, we also used a
sub() function for replacing the given pattern with a string or a result of a specified function.