Click to See Complete Forum and Search --> : Python and replace/regexps


sonictooth
12-07-2002, 06:15 AM
So i'm trying to write a cgi blog type interface in python. Which has turned out to be alot of pain and humilitaition but rewarding when somethign works.

however i can't figure this problem out.

i want to open a file and replace content within the file. Now doing a .replace or regexp on a .read of the file and then .write that only over writes it up until the input stream stops. I want to completely replace it. for instance:

file:
various users and text

replaced file:
small text

not:
small textsers and text

i tried using the os module to delete the file and the touch and chmod a new one then write to it. But that gets very iffy with permissions and usually doesn't work.

the pratical application of this would be writing to a html file. I want to replace the text between to <!--CONTENT--> comments i put in. but after it does it now i end up with something like this:
</html>
="password">etc... various stuff from before the replacement.

because the replaced text was longer then what i am replacing it with. isn't there a way to just replace and delete everything in a regexp sort of way while writing to a file?

[EDIT]
i solved it, you need to envoke the truncate flag when writing

f = open('file','w+')
f.write('stuff')

that replaces the file with with stuff... completely

so you might want to read the file, then change the read buffer then write it all back