Regular expression worries

Bruno Desthuilliers onurb at xiludom.gro
Wed Oct 11 18:10:52 CEST 2006


CSUIDL PROGRAMMEr wrote:
> folks
> I am new to python, so excuse me if i am asking stupid questions.

>From what I see, you seem to be new to programming in general !-)

> I have a txt file  and here are some lines of it
> 
> Document<Keyword<date:2006-08-19> Keyword<time:11:00:43>
> Keyword<username:YOURBOTNICK> Keyword<data:localhost.localdomain>
> Keyword<logon:localhost.localdomain
>   > Keyword<date:2006-08-19> Keyword<time:11:00:44> Keyword<sender:>
> Keyword<receiver:> Keyword<data::+iwx> Keyword<mode::+iwx
> 
> I am writing a python program to replace the tags and word  Document
> with Doc.
> 
> Here is my python program
> 
> #! /usr/local/bin/python
> 
> import sys
> import string
> import re
> 
> def replace():
>   filename='/root/Desktop/project/chatlog_20060819_110043.xml.txt'
>   try:
>     fh=open(filename,'r')
>   except:
>     print 'file not opened'
>     sys.exit(1)

You open your file a first time, and bind the reference to the file
object to fh.

>   for  l in
> open('/root/Desktop/project/chatlog_20060819_110043.xml.txt'):

And then you open the file a second time...

>       l=l.replace("Document", "DOC")

This modifies the string referenced by l (talk about a bad name) and
rebind to the same name

>       fh.close()

Then you close fh... and discard the modifications to l.

> if __name__=="__main__":
>   replace()
> 
> But it does not replace Document with Doc in  the txt file

Why should it ? You didn't asked for it !-)

> Is there anything wrong i am doing

Yes.

The canonical way to modify a text file is to read from original / do
transformations / *write modifications to a tmp file* / replace the
original with the tmp file.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list