Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a line from a text file using the line number in python

here is an example text file

the bird flew
the dog barked
the cat meowed

here is my code to find the line number of the phrase i want to delete

phrase = 'the dog barked'

with open(filename) as myFile:
    for num, line in enumerate(myFile, 1):
        if phrase in line:
            print 'found at line:', num

what can i add to this to be able to delete the line number (num) i have tried

lines = myFile.readlines()
del line[num]

but this doesnt work how should i approach this?

like image 592
derpyherp Avatar asked Jul 19 '13 13:07

derpyherp


People also ask

How do you remove a line from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do I delete a file line?

Sed Command to Delete Lines – Based on Position in File In the following examples, the sed command removes the lines in file that are in a particular position in a file. Here N indicates Nth line in a file. In the following example, the sed command removes the first line in a file.


1 Answers

You could use the fileinput module to update the file - note this will remove all lines containing the phrase:

import fileinput

for line in fileinput.input(filename, inplace=True):
    if phrase in line:
        continue
    print(line, end='')
like image 158
Jon Clements Avatar answered Oct 13 '22 01:10

Jon Clements