File I/O
Ant
antroy at gmail.com
Sat Sep 30 03:58:59 EDT 2006
Kirt wrote:
...
> i dont wanna parse the xml file..
>
> Just open the file as:
>
> f=open('test.xml','a')
>
> and append a line "<Body2>abc</Body2>" before tag </Top>
The other guys are right - you should look at something like
ElementTree which makes this sort of thing pretty easy, and is robust.
But if you are sure that:
1) </Top> is going to be on its own line (rather than something like
</Body1></Top>)
2) the ending tag will *definitely* have no extraneous whitespace (e.g.
< / Top >)
then the following will probably be the simplest solution:
f=open('test.xml')
out = []
for line in f:
if "</Top>" in line:
out.append("<Body2>abc</Body2>")
out.append(line")
f.close()
f_out = open("test.xml", "w")
f.write("".join(out))
f_out.close()
If you're working with XML in any sort of quantity, then look into the
available XML tools - it will be worth your time.
More information about the Python-list
mailing list