[Tutor] Working with files
alan.gauld at freenet.co.uk
Fri Aug 26 14:02:22 CEST 2005
> basically I took the idea and the code example given and wrote this
> little function, i stuck vars in this html page like #email# and
> just used it like this, " insertdata('#email#','scott at python.org')
> works perfect!
ARe you sure? The problem using seek and write is that if the data
you are inserting is bigger than your marker you will overwrite the
data following the marker.
Thus if your marker were in a table like:
And you overwrite the #mail# with scott at python.org
You will end up with:
<TR><TD>scott at python.orgScott's email</TD></TR>
Which will not display the way you want!
> def insertdata(name, data):
> file = open('template.html', 'r+')
> contents = file.read()
> pos = contents.index(name)
This does not insert it overwrites.
You are better to insert the content into contents and
then just write it all back to the file in one move.
> file.write(contents[pos + len(name):])
Author of the Learn to Program web tutor
More information about the Tutor