How to Delete Specific Line from a Text File in Python?


In this article, we will show you how to delete a specific/particular line from a text file using python.

Assume we have taken a text file with the name TextFile.txt consisting of some random text. We will delete a particular line (for example line 2) from a text file

TextFile.txt

Good Morning
This is Tutorials Point sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome everyone
Learn with a joy

Algorithm

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the path of the text file.

  • Use the open() function(opens a file and returns a file object as a result) to open the text file in read-only mode by passing the file name, and mode as arguments to it (Here “r” represents read-only mode).

with open(inputFile, 'r') as filedata:
  • Using the readlines() function (returns a list with each line in the file represented as a list item. To limit the number of lines returned, use the hint argument. No more lines are returned if the total amount of bytes returned exceeds the specified number) to obtain the list of lines of a given input text file.

file.readlines(hint)
  • Create a variable (which holds the line number) and initialize its value to 1.

  • Use the open() function(opens a file and returns a file object as a result) to open the given text file in write mode by passing the file name, and mode as arguments to it (Here “w” represents write mode).

with open(inputFile, 'w') as filedata:
  • Traverse in each line of the file using the for loop.

  • Enter the line number to be deleted as dynamic input using the input() function (The input() function reads a line from the input (from the user), converts it to a string by eliminating the trailing newline, and returns it. When EOF is encountered, an EOFError exception is thrown) and type casting it to an integer using the int() function(converts to an integer).

  • Using the if conditional statement, determine whether the line index(line number) is not equal to a given delete line number.

  • If the condition is true, then use the write() function(writes a specified text to a file. The provided text will be inserted depending on the file mode and stream position) to write that corresponding line into a file.

  • Increase the value of the line index(line number) value by 1.

  • Print some random text if the given particular line is deleted successfully.

  • Open the input file again in read mode using the open() function to print the file content after deleting the given particular line.

  • Traverse in each line of the file using the for loop.

  • Print each line of the text file.

  • Close the input file with the close() function(used to close an opened file).

Example

The following program to delete a given line from a text file and print the result file content after deleting that line −

# input text file inputFile = "TextFile.txt" # Opening the given file in read-only mode. with open(inputFile, 'r') as filedata: # Read the file lines using readlines() inputFilelines = filedata.readlines() # storing the current line number in a variable lineindex = 1 # Enter the line number to be deleted deleteLine = int(input("Enter the line number to be deleted = ")) # Opening the given file in write mode. with open(inputFile, 'w') as filedata: # Traverse in each line of the file for textline in inputFilelines: # Checking whether the line index(line number) is # not equal to a given delete line number if lineindex != deleteLine: # If it is true, then write that corresponding line into file filedata.write(textline) # Increase the value of line index(line number) value by 1 lineindex += 1 # Print some random text if the given particular line is deleted successfully print("Line",deleteLine,'is deleted successfully\n') # Printing the file content after deleting the specific line print("File Content After Deletion :") # Reading the file again in read mode givenFile = open(inputFile,"r") # Traversing the file line by line for line in givenFile: # printing each line print(line) # Closing the input file filedata.close()

Output

On executing, the above program will generate the following output −

Enter the line number to be deleted = 2
Line 2 is deleted successfully

File Content After Deletion :
Good Morning
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome everyone
Learn with a joy

We gave our program a text file containing some random content and then opened it in reading mode. We created a variable to store the current line number and initialized it to 1, the starting line number. We traversed the file until we reached the end, then checked to see if the user input number was equivalent to the line number that was to be deleted. If it is false, we do not need to delete or remove that line, thus we write it to the file. Instead of deleting the specified line, we add the remaining lines to the file, thus the removed line does not appear in the result file. For every line, the value of the line number is increased by one.

In this article we have learned about how to delete a specific line from a text file and save the remaining lines in the same article. Along with that we have learned about how to traverse the entire text file from start to end, as well as how to read and write the data into text file.

Updated on: 01-Aug-2022

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements