[Tutor] Working with files

Scott Oertel me at scottoertel.info
Thu Aug 25 23:55:51 CEST 2005

Bob Gailer wrote:

> At 02:55 PM 8/24/2005, Scott Oertel wrote:
>> How do I use the built in file objects to insert text into a file at a
>> certain location?
>> i.e.
>> something, 2, chance, weee
>> nothing, happened, crap, nice
>> .... need to search for "something" and insert, "what," before it
> Here's the algorithm. If you know enough Python you will be able to 
> code it. So put together a program, give it a try and come back with 
> questions.
> read the file into a string variable (assuming the file is not humungus)
> find the location of "something" in the string
> assemble a new string consisting of:
>   the original string up to the location (index) of "something"
>   "what"
>   the rest of the original string
> write the new string to the file
> Bob Gailer
> 303 442 2625 home
> 720 938 2625 cell

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!

def insertdata(name, data):
    file = open('template.html', 'r+')
    contents = file.read()
    pos = contents.index(name)
    file.write(contents[pos + len(name):])

More information about the Tutor mailing list