Delete a certain line from a file

Carel Fellinger cfelling at iae.nl
Tue Feb 13 09:41:35 EST 2001


Gustaf Liljegren <gustafl at algonet.se> wrote:
> Excuse another newbie question. My script is reading a textfile with a list
> of words (separated with newlines), and now I need something to delete a
> certain record when I encounter it in a loop. Something like:

> for line in f.readlines():
>   if line == "somethingbad":
>     # delete the whole line with newline
>     break

use the marvelous fileinput module like in:

    import fileinput

    for line in fileinput.input('yourfile', inplace=1):
        if line != "somethingbad":
            print line,

The keyword argument "inplace=1", tells fileinput.input to handle this
file special: make a copy, read from that copy and redirect stdout to
a new version of that file, effectively allowing you to change that
file `in place'.  Notice the trailing "," in the print line, this tells
print not to add (yet an other) end-of-line character.


> I have successfully done this by adding each line to a list and then used
> list.remove("somethingbad"), but there's another way without having to put
> the whole file in a list, isn't it?

see above:),
your approach seems correct though, though could be spedup a little:

    data = filter(lambda x: x != "somethingbad", f.readlines())

or:

    data = []
    for line in f.readlines()
        if line != "somethingbad"
            data.append(line)
-- 
groetjes, carel



More information about the Python-list mailing list