1

What's the easiest way to write an edited XML root to a new file? This is what I have so far and it's throwing AttributeError: 'module' object has no attribute 'write'
PS: I can't use any other api besides ElementTree.

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment
from ElementTree_pretty import prettify
tree = ET.parse('file-to-be-edited.xml')
root = tree.getroot()

#Process XML here

ET.write('file-after-edits.xml')
user1195192
  • 679
  • 3
  • 11
  • 19

2 Answers2

1

AttributeError: 'module' object has no attribute 'write' is saying that you cannot call the write method directly from ElementTree class, it is not a static method, try using tree.write('file-after-edits.xml'), tree is your object from ElementTree.

1

Your tree is a ElementTree object which provides a write() method to write the tree. For example:

#Process XML here
tree.write('file-after-edits.xml', encoding='utf8')
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Thanks for the solution. Silly mistake on my part. Is there any way possible to prettify the generated file? – user1195192 Sep 06 '16 at 02:46
  • You could use [`lxml`](http://lxml.de/) which provides a compatible API to that of `ElementTree`. Its `tree.write()` method accepts a `pretty_print=True` argument. – mhawke Sep 06 '16 at 12:27
  • Or use `minidom`, see: http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python – mhawke Sep 06 '16 at 12:29