Chapter 15
data = [Pair(2,3), Pair(5,7)]
serialize_csv(""test"", data)
b'x,y\r\n2,3\r\n5,7\r\n'
""""""
buffer= io.StringIO()
wtr= csv.DictWriter(buffer, Pair._fields)
wtr.writeheader()
wtr.writerows(r._asdict() for r in data)
return buffer.getvalue()
The CSV module's readers and writers are a mixture of imperative and functional
elements. We must create the writer, and properly create headings in a strict
sequence. We've used the _fields attribute of the Pair namedtuple to determine
the column headings for the writer.
The writerows() method of the writer will accept a lazy generator function.
In this case, we used the _asdict() method of each Pair object to return a
dictionary suitable for use with the CSV writer.
Serializing data into XML
We'll look at one approach to XML serialization using the built-in libraries. This will
build a document from individual tags. A common alternative approach is to use
Python introspection to examine and map Python objects and class names to XML
tags and attributes.
Here's our XML serialization:
import xml.etree.ElementTree as XML
def serialize_xml(series, data):
""""""
data = [Pair(2,3), Pair(5,7)]
serialize_xml(""test"", data)
b'<series name=""test"">
""""""
doc= XML.Element(""series"", name=series)
for row in data:
row_xml= XML.SubElement(doc, ""row"")
x= XML.SubElement(row_xml, ""x"")