ElementTree.write doesn't really matter in the second pass

I had a problem with xml formatting when writing to an xml file. The problem is that the first time I write to an xml file, the xml is formatted correctly using pretty_print = True. Any subsequent attempts to add to the xml file are not formatted properly. Xml is written but not formatted. My code looks like this:

#does the library.xml file exist?
if os.path.isfile(libraryFile):
    library = ET.ElementTree()
    library.parse(libraryFile)
else:
    #the library.xml does not exist at the given path
    library = ET.ElementTree(project.getBoilerplateLibrary(path)) 

root = library.getroot()

root.append(xml) #xml is a lxml Element object

f = open(libraryFile, 'w')
library.write(f, pretty_print=True)
f.close()

The first time we write to a file, I get something like:

<root>
    <element>
        <foo>bar</foo>
    </element>
</root>

Any subsequent attempts to add to this file are as follows:

<root>
    <element>
        <foo>bar</foo>
    </element><element><bleep>bloop</bleep></element></root>

Any ideas?

+3
source share
1 answer

Frequently asked questions relate to this question: Why don't the good print settings reformat my XML output

/fooobar.com/... lxml pretty print write.

, , XML, ( ).

+1

All Articles