[Tutor] Removing something from a file
Charlie Clark
charlie@begeistert.org
Thu, 04 Apr 2002 20:38:46 +0200
On 2002-04-04 at 19:00:09 [+0200], tutor-request@python.org 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.
>
for line in inp.readlines():
if x is in inp.readlines del x
del removes an item from a sequence. This might work if a single line = x but not otherwise. Furthermore, you don't need to do this for every line. The syntax if wrong anyway.
if x in inp.readlines(): # this may return None as you are calling it again
print x, "is in the file"
You can only use "in" to check for membership in a sequence.
If you want to remove entire lines 'spam' you could try this
for line in inp.readlines():
if line != 'spam':
outp.write(line)
if you just want to remove 'spam' from the file you don't even need to loop
content = inp.read()
content = content.replace('spam', '')
outp.write(content)
That any help?
Charlie