title: Writing just the xml declaration to file using Python
body: <p>I am writing multiple xml files in python by looping over lists of strings.
  Suppose I have:</p>
  
  <pre><code>from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
  
  parent = Element('parent')
  child = SubElement(parent, 'child')
  f = open('file.xml', 'w')
  document = ElementTree(parent)
  l = ['a', 'b', 'c']
  for ch in l:
      child.text = ch
      document.write(f, encoding='utf-8', xml_declaration=True)
  </code></pre>
  
  <p>The output: </p>
  
  <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;
  &lt;parent&gt;&lt;child&gt;a&lt;/child&gt;&lt;/parent&gt;&lt;?xml version='1.0' encoding='utf-8'?&gt;
  &lt;parent&gt;&lt;child&gt;b&lt;/child&gt;&lt;/parent&gt;&lt;?xml version='1.0' encoding='utf-8'?&gt;
  &lt;parent&gt;&lt;child&gt;c&lt;/child&gt;&lt;/parent&gt;
  </code></pre>
  
  <p>Desired output:</p>
  
  <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;
  &lt;parent&gt;
  &lt;child&gt;a&lt;/child&gt;
  &lt;child&gt;b&lt;/child&gt;
  &lt;child&gt;c&lt;/child&gt;
  &lt;/parent&gt;
  </code></pre>
  
  <p>I only want the xml declaration to appear one time, at the top of the file. Probably should write the declaration to the file before the loop, but when I attempt that, I get empty elements. I do not want to do this:</p>
  
  <pre><code>f.write('&lt;?xml version='1.0' encoding='utf-8'?&gt;')
  </code></pre>
  
  <p>How to write just to xml declaration to the file?</p>
  
  <p>Edit: Desired output</p>