I have an html file and I am parsing it with regular expressions. I don't want to use any python html libraries, because I am not using it as a website, but as a configuration type file. I am making a basic bookmarks system, the parser works fine, so I guess my question is about the second part, writing to the files. The file looks like this

<title>my bookmarks</title>
<div id="smalltalk">
<a href="http://www.smalltalk.org">Smalltalk.org</a>
<div id="python">
<a href="http://www.python.org">Python.org</a>

My parser call the div's sections, and I want to write a method to insert more sections before the /body and /html tags.

The question, without all of my other information is, how do I INSERT text into a file with python, without deleting the text after it.

Well, I dont know where you want to insert the text, aka: between the <body> and </body> or between the </body> and </html> but, if you need to write at a specific line you could always copy the text before you write to it, then append the file with open(file, 'a') and then add the text you have copied before, maybe like so(write after the </body> tag):

FILE = open('file.txt', 'a')
lines = FILE.readlines()
#Find the </body> line
for line in lines:
    if line == "</body>":
#Write to the list
lines.insert(lineNum+1, "Data, text, or anything you need to insert!")
#Open file and clear it
FILE = open('file.txt', 'w')
#Write old data and new data (in list: lines)
for line in lines:

Thank you, I didn't see an insert method anywhere on the python reference! I will see if the code works, then get back to you!

o, i see what you are doing, i cant quite get it to work, but, thank you for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.