Using multiple contexts for reading and writing files
It's common to need to convert data from one format to another. For example, we might have a complex web log that we'd like to convert to a simpler format.
See the Reading complex formats using regular expressions recipe for a complex web log format. We'd like to do this parsing just one time.
After that, we'd like to work with a simpler file format, more like the format shown in the Upgrading CSV from dict reader to namedtuple reader or Upgrading CSV from dict reader to namespace reader recipe. A file that's in CSV notation can be read and parsed with the csv
module, simplifying the physical format considerations.
How can we convert from one format to another?
Getting ready
Converting a file of data from one format to another means that the program will need to have two open contexts: one for reading and one for writing. Python makes this easy. The use of with
statement contexts assures that the files are properly closed and all of the related...