[Tutor] Working with files

Sean 'Shaleh' Perry shalehperry@attbi.com
Thu, 04 Apr 2002 09:09:01 -0800 (PST)


On 04-Apr-2002 Eve Kotyk wrote:
> How do you open a file, read the file, remove an element in the file and
> write it to a backup file.
> 
> I can do all of this from the following code from Alan's tutorial except
> delete part of the file before rewriting it.
> 
> inp = open('menu.txt', 'r')
> outp = open('menu.bak', 'w')
> for line in inp.readlines():
>       #here I would like to say that x = "spam'
>       #if x is in inp.readlines del x
>       #it seems to me that it doesn't act on the line, it just deletes x.  I
> can't             #figure out any way to have it del x from line and then
> write this line.      outp.write(line)
> inp.close()
> outp.close()
> 

import re

for line in inp.readlines():
  if re.search(r'Canada', line): continue # if line contains 'Canada'
  outp.write(line)