def modify(self, portsFileContentModifyingMethod): """Recommended safe wrapper to modify .ports file. Does nothing in case file doesn't exist on the host disk. Intentionally does nothing to support installation policies where .ports files are not to be stored. To make sure file exists, call create().""" # help avoid trouble if not self.exists(): # intentionally not self.create() return # read existing file with codecs.open(self._portsFilePath, "r", encoding="utf-8") as inputFile: portsFileContent = ElementTree(file=inputFile) # modify portsFileContentModifyingMethod(portsFileContent) # overwrite with codecs.open(self._portsFilePath, "w", encoding="utf-8") as outputFile: # from Python 2.7 and ElementTree 1.3 on with xml_declaration=True # portsFileContent.write(outputFile, encoding="utf-8") outputFile.write( ElementTreeUtil.tostring(portsFileContent, indent=" ", xml_declaration=True, encoding="utf-8") ) # keep up-to-date self._load()
def create(self): """Create a .ports file. As implemented creates an empty container. Does nothing in case file already exist on the host disk.""" if self.exists(): # intentionally not raise Exception("won't overwrite already existing {0}".format(self._portsFilePath)) return # just an empty container ports = Element("ports") portsFileContent = ElementTree(ports) # # write with codecs.open(self._portsFilePath, "w", encoding="utf-8") as outputFile: # from Python 2.7 and ElementTree 1.3 on with xml_declaration=True # portsFileContent.write(outputFile, encoding="utf-8") outputFile.write( ElementTreeUtil.tostring(portsFileContent, indent=" ", xml_declaration=True, encoding="utf-8") ) # keep up-to-date self._load()