Categories
Python

How to delete a line in text file using Python

Last updated on February 21st, 2022 at 10:26 am

Click to rate this tutorial!
[Total: 8 Average: 3.5]

Text file processing :- How to delete a line in text file using Python

Let us start by creating a simple text file ‘myfile‘, Content of the file is as follows.

python-text-file-processing
This is the first line
Second line
The third line
I love Python
I love PHP
Text file processing

The python script we are going to create will delete a specific line starting with the word defined. The line to be deleted is assigned to the variable “str“. Save the code as “delete.py

#!/usr/bin/python
def deleteLine():
 fn = 'myfile'
 f = open(fn)
 output = []
 str="The"
 for line in f:
   if not line.startswith(str):
    output.append(line)
 f.close()
 f = open(fn, 'w')
 f.writelines(output)
 f.close()
deleteLine()

In this script we are going to delete third line which starts with “The“, Hence we assign ‘str=”The”‘. You can change this value to any according to your requirement.

How function deleteLine() works?

1)Inside this function we are defining the file name “myfile”
2)Open the file
3)Assign an array named output.
4)Assign ‘str’ to line which needs to be deleted.
5)Then reading each line and appending all lines to output array which doesn’t start with line “The”
6)We are closing the file using f.close()
7)Next step is to open the file again and write data which is saved to “output” array to the same file.
8)Note that in this specific example we are opening the file reading each line and then saving in to output array. Then open same file again and write data to it. Last step is to call this function deleteLine()

Output: As you can see below after running the python script line starting with “The” got deleted.

$ cat myfile
This is the first line
Second line
The third line
I love Python
I love PHP
Text file processing
$./delete.py
$cat myfile
This is the first line
Second line
I love Python
I love PHP
Text file processing
$

 It is very simple and I am not going to confuse you with any other steps. Hope this script will be useful for some of you around .

Click to rate this tutorial!
[Total: 8 Average: 3.5]

One reply on “How to delete a line in text file using Python”

Leave a Reply

Your email address will not be published.