Choosing a data format
You already know CSV and JSON. Python's standard library understands more formats, and each one was born for a different use…
Besides CSV and JSON, Python reads and writes other very common formats. In this lesson you will work with XML (ElementTree), with INI and TOML configuration files, and with pickle to save Python objects. You will learn to choose the right format for each case, to generate XML without breaking the document, to read configuration with default values and to avoid the security risk of loading untrusted pickles.
You already know CSV and JSON. Python's standard library understands more formats, and each one was born for a different use…
XML represents data as a tree of elements . Each element has a tag, optional attributes, text and other child elements…
To produce XML you do not paste text with f-strings: an & or a < in a piece of data would break the document. You build the tree…
Programs need settings that can be changed without touching the code: paths, ports, options. Two simple text formats for that are…
pickle converts almost any Python object (lists, dictionaries, sets, tuples, instances of your classes…) into bytes and rebuilds…
XML organizes data in a tree of elements with tags, attributes and text. The xml.etree.ElementTree module turns them into objects…
Walking the whole tree of an XML document is as simple as iterating over the root element with iter() .
An XML document is a tree, and trees are processed with recursive functions: the depth of an element is 1 plus the greatest depth…
To create XML you do not concatenate text: you build the tree with Element and SubElement , and tostring takes care of escaping…
INI files store configuration in [section] sections with key = value pairs. The configparser module reads them and lets you give…
With ConfigParser you can also generate INI files: you create sections, assign keys and save it with write .
TOML is the modern configuration format of Python ( pyproject.toml uses it). With tomllib (Python 3.11+) a file becomes…
Data coming from outside can be invalid. tomllib.loads raises TOMLDecodeError if the TOML text is malformed, and a robust program…
pickle serializes almost any Python object to bytes and rebuilds it later. It is handy between your own programs, but you must…
Converting XML into Python structures (and then into JSON) is a common integration task between systems. It needs recursion and…