file handling from each match of the incident_re regular expression we then extract all the key=value strings in one go using the keyvalues match groupand apply the key_value_re regular expression' re finditer(method to iterate over each individual key=value line for each (keyvaluepair foundwe put them in the data dictionary--so all the values go in as strings thenfor those values which should not be stringswe replace them with value of the appropriate type using the same string conversions that we used when parsing the text manually we have added check to ensure that the data dictionary has nine items because if an incident record is corruptthe key_value finditer(iterator might match too many or too few key=value lines the end is the same as before--we create new incident object and put it in the incidents dictionarythen return true if anything went wrongthe except suite will issue suitable error message and return falseand the finally suite will close the file one of the things that makes both the manual and the regular expression text parsers as short and straightforward as they are is python' exceptionhandling the parsers don' have to check any of the conversions of strings to datesnumbersor booleansand they don' have to do any range checking (the incident class does thatif any of these things failan exception will be raisedand we handle all the exceptions neatly in one place at the end another benefit of using exception-handling rather than explicit checking is that the code scales well--even if the record format changes to include more data itemsthe error handling code doesn' need to grow any larger writing and parsing xml files ||some programs use an xml file format for all the data they handlewhereas others use xml as convenient import/export format the ability to import and export xml is useful and is always worth considering even if program' main format is text or binary format out of the boxpython offers three ways of writing xml filesmanually writing the xmlcreating an element tree and using its write(methodand creating dom and using its write(method similarlyfor reading and parsing xml files there are four out-of-the-box approaches that can be usedmanually reading and parsing the xml (not recommended and not covered here--it can be quite difficult to handle some of the more obscure and advanced details correctly)or using an element treedomor sax parser in additionthere are also third-party xml libraries availablesuch as the lxml library mentioned in ( )that are well worth investigating the aircraft incident xml format is shown in figure in this section we will show how to write this format manually and how to write it using an element tree and domas well as how to read and parse this format using the element