cElementTree clear semantics

Fredrik Lundh fredrik at pythonware.com
Sun Sep 25 22:21:26 CEST 2005


Igor V. Rafienko wrote:

> The problem is that the file looks like this:
>
> <data>
    ... lots of schnappi records ...

okay.  I think your first approach

    from cElementTree import iterparse

    for event, elem in iterparse("data.xml"):
        if elem.tag == "schnappi":
            count += 1
            elem.clear()

is the right one for this case.  with this code, the clear call will
destroy each schnappi record when you're done with it, so you
will release all memory allocated for the schnappi elements.

however, you will end up with a single toplevel element that
contains a large number of empty subelements.  this is usually
no problem (it'll use a couple of megabytes), but you can get
rid of the dead schnappis too, if you want to.  see the example
that starts with "context = iterparse" on this page

    http://effbot.org/zone/element-iterparse.htm

for more information.

</F>






More information about the Python-list mailing list