Delete a certain line from a file

Steve Purcell stephen_purcell at
Tue Feb 13 15:39:06 CET 2001

Gustaf Liljegren 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

Note that 'readlines' always reads the whole file into memory anyway...

> 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?

Yes, filter the file into another file then rename it:

  infile = open(inputfilename,'r')
  outputfile = open(outputfilename, 'w')

  while 1:
    line = infile.readline()
    if not line: break
    if line != "somethingbad":

  os.rename(outputfilename, inputfilename)


Steve Purcell, Pythangelist
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright

More information about the Python-list mailing list