File I/O

uche.ogbuji at gmail.com uche.ogbuji at gmail.com
Fri Oct 6 20:13:10 CEST 2006


Ant wrote:
> 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()

And the most dangerous solution.  Start with the line
"out.append(line")"

And have a look at the many failure possibilities I detail here:

http://www.xml.com/pub/a/2002/11/13/py-xml.html

Then add to that the fact that "</Top>" can legitimately appear in an
XML comment, so that logic is even more brittle.

The following code does this *safely* with Amara:

import amara
doc = amara.parse('test.xml')
top = doc.xml_xpath('//Top')[0]
top.xml_parent.xml_insert_before(top, doc.xml_create_element(u'Body2',
content=u'abc'))
top.xml(stream=open('test.xml', 'w'))

Amara: http://uche.ogbuji.net/tech/4suite/amara/


--
Uche Ogbuji                               Fourthought, Inc.
http://uche.ogbuji.net                    http://fourthought.com
http://copia.ogbuji.net                   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/




More information about the Python-list mailing list