Python Read File Into String Replace New Line
Supplant a Line in a File in Python
- Use the
for
Loop Along With thereplace()
Office to Supplant a Line in a File in Python - Create a New File With the Refreshed Contents and Replace the Original File in Python
- Use the
fileinput.input()
Function for Replacing the Text in a Line in Python - Utilize the
re
Module to Supercede the Text in a Line in Python
File handling is considered an essential aspect of any spider web awarding. Like to most programming languages, Python is perfectly capable of supporting file handling. It allows you lot to deal with files of different types, essentially to perform some bones operations like reading and writing. Information technology also provides some other file handling options to operate the files.
This tutorial demonstrates the different methods available to supercede a line in a file in Python.
To demonstrate the unlike ways to replace a line in a file in this article, we will take a text file, motivation.txt
.
Text file (motivation.txt
):
At that place are always 2nd chances in life. Everyone can bounce back from hardships. The hardships that we face up are just a test to check our will. A stiff volition 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 appropriately.
Use the for
Loop Along With the replace()
Function to Replace a Line in a File in Python
The open()
function is utilized to open a file in Python. The file can exist opened in either format of text or binary, which depends on the developer. The open()
role has various modes, and all of them provide dissimilar accessibility options to open a file.
The uncomplicated for
loop is a conventional manner to traverse through every line in the given text file and find the line we want to replace. And so, the desired line can be replaced by using the replace()
function. All of this is washed in the read
way. 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 forth with the supplant()
function.
# 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 + "\northward" file.shut() # opening the file in write way fout = open("motivation.txt", "w") fout.write(replacement) fout.shut()
Create a New File With the Refreshed Contents and Supercede the Original File in Python
Several functions are at piece of work to implement this process. The knowledge of the process of all these functions is necessary to execute this method successfully. Nosotros need to import several functions from three modules to the Python lawmaking.
- Firstly, we need to import the
mkstemp()
role from thetempfile
module. This role is utilized to return a tuple every bit an output along with a path and a file descriptor.- Then, we need to import two functions from the
shutil
module. The showtime function is thecopymode()
office, which is utilized in copying the permission bits from a source to the destination path. The second role is themotion()
function, which allows the motion of files from one place to another.
- Then, we need to import two functions from the
- Finally, we need to import the
remove()
part from theOS
module. This function allows the deletion of a path.
All these modules need to be imported to the electric current Python code to run the code without whatever errors. An case code that implements this style 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 every bit 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,'due west') as file1: with open(filepath,'r') as file0: for line in file0: file1.write(line.supersede(hardships,situations)) copymode(filepath, abspath) remove(filepath) move(abspath, filepath) replacement(path,'hardships','situations')
Employ the fileinput.input()
Function for Replacing the Text in a Line in Python
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
modules need to be imported to the current Python lawmaking in society 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.supplant(previousw, nextw) sys.stdout.write(line) var1 = "hardships" var2 = "situations" file = "motivation.txt" replacement(file, var1, var2)
Use the re
Module to Replace the Text in a Line in Python
The 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, nosotros use ii functions, namely, re.compile()
and re.escape()
, from the RegEx
module. The re.compile()
role is utilized to generate a regular expression object from the regular expression pattern, which is and so 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)
Hither, nosotros also used a sub()
part for replacing the given pattern with a cord or a outcome of a specified function.
Write for us
DelftStack articles are written by software geeks like you. If yous also would like to contribute to DelftStack past writing paid articles, you can check the write for us page.
Related Article - Python File

Source: https://www.delftstack.com/howto/python/python-replace-line-in-file/
0 Response to "Python Read File Into String Replace New Line"
Post a Comment