How to Delete Specific Line from a Text File in Python?In the following tutorial, we will learn the method of deleting a specific line from a text file in the Python programming language. So, let's get started. Removing Specific Line from Text FileLet's say we have a text file called TextFile.txt that contains some random content. We are going to remove a certain line (let's say line 2) from a text DOCUMENT. TextFile.txt Algorithm: The stages and algorithm to achieve the desired goal are listed below −
with open(inputFile, 'r') as file data:
file.readlines(hint)
with open(inputFile, 'w') as file data:
Example: The program that follows may be used to remove a specific line from a text file and then print the contents of the result file. Output: When the program above runs, it will provide the following results: Line 2 is deleted successfully File Content After Deletion : Hello Everyone. This is a sample file. We are happy to learn Python from Javatpoint. The Resources from this website are incredible. Everything we have learned so far helped us in our career. We should learn new technologies everyday and enhance our knowledge and develop our skills to be in the competition. We opened a text file with some random content in our program's reading mode after providing it with it. The starting line number, 1, was the first value of the variable we established to hold the current line number. After reading through the whole file, we made sure the number entered by the user matched the line that needed to be removed. If the answer is false, we write it to the file instead of deleting or removing it. The eliminated line does not show in the output file because we added the remaining lines to the file rather than removing the specified line. The value of the line number increases by one for each line. ConclusionThis article explains how to remove a particular line from a text file while keeping the rest of the content intact. We also learned how to read and write data into text files and navigate through a text file from beginning to end. Next TopicHow to dockerize a python script |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India