Here's an approach that uses Python properties to auto-save the XML.
import xml.etree.ElementTree as ET
class ProgramProperties(object):
def __init__(self, xmlfile):
# Parse the XML file
self.__xmlfile = xmlfile
self.__xml_tree = ET.parse(xmlfile)
self.__version_element = self.__xml_tree.getroot().find(".//property[@name='version']")
# Get an in-memory copy of 'version'
self.__version = float(self.__version_element.text)
@property
def version(self):
return self.__version
@version.setter
def version(self, vers):
# Avoid unecessary file I/O
if self.__version != vers:
# Store in-memory
self.__version = vers
# Save the version to the file
self.__version_element.text = str(vers)
self.__xml_tree.write(self.__xmlfile)
prog = ProgramProperties('testdata.txt')
# Update the version, which automatically saves it in the setter
prog.version = 3.14