File I/O

Ant antroy at
Sat Sep 30 09:58:59 CEST 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
2) the ending tag will *definitely* have no extraneous whitespace (e.g.
< / Top >)

then the following will probably be the simplest solution:

out = []
for line in f:
    if "</Top>" in line:


f_out = open("test.xml", "w")

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