Python writing to an xml file
<p>I am trying to write to an xml file.  I have changed a specific element in my code, and am able to get it to print successfully.  I need to have it written to the file, without changing the structure of the file.<br>
My code:</p>

<p>import os
from lxml import etree</p>

<pre><code>directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
    if f.endswith(".xml"):

        xmlfile = directory + '/' + f



        tree = etree.parse(xmlfile, parser=XMLParser)
        root = tree.getroot()

        hardwareRevisionNode = root.find(".//hardwareRevision")



        if hardwareRevisionNode.text == "5":
            print " "
            print "Old Tag: " + hardwareRevisionNode.text

            x = hardwareRevisionNode.text = "DVT2"

            print "New Tag " +  hardwareRevisionNode.text
</code></pre>

<p>When I try various methods of opening and closing the file, it just deletes all the data in the xml file.  Using this method </p>

<pre><code>outfile = open(xmlfile, 'w')
oufile.write(etree.tostring(tree))
outfile.close()
</code></pre>

<p>Changed the code structure of my file to be one long line.</p>

<p>To get newlines in the output file, it looks like you need to pass <a href="http://lxml.de/tutorial.html#serialisation" rel="nofollow"><code>pretty_print=True</code></a> to your sterilization (<code>write</code> or <code>tostring</code>) call.</p>

<p>Side note; Normally, when you open files with python you open them like this:</p>

<pre><code>with open('filename.ext', 'mode') as myfile:
    myfile.write(mydata)
</code></pre>

<p>This way there is less risk of file descriptor leaks. The <a href="http://stackoverflow.com/a/3605831/1342445"><code>tree.write("filename.xml")</code></a> method looks like a nice and easy way to avoid dealing with the file entirely.</p>

python xml lxml elementtree