Data formats: XML, INI, TOML and pickle · 1 / 15 Theory

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. Choosing well avoids conversions and mistakes.

import json, tomllib, configparser
import xml.etree.ElementTree as ET

# The same data in four formats
as_json = '{"name": "ana", "age": 30}'
as_xml = '<person><name>ana</name><age>30</age></person>'
as_ini = """
[person]
name = ana
age = 30
"""
as_toml = """
name = "ana"
age = 30
"""

print(json.loads(as_json))                      # {'name': 'ana', 'age': 30}
print({h.tag: h.text for h in ET.fromstring(as_xml)})   # {'name': 'ana', 'age': '30'}
cfg = configparser.ConfigParser()
cfg.read_string(as_ini)
print(dict(cfg["person"]))                        # {'name': 'ana', 'age': '30'}
print(tomllib.loads(as_toml))                    # {'name': 'ana', 'age': 30}
FormatBest forModuleNotes
CSVTables of rows and columnscsvNo types: everything is text
JSONExchange between programs and APIsjsonLists, dictionaries, numbers, text
XMLStructured documents with attributesxml.etree.ElementTreeVerbose; common in older systems
INISimple configuration in sectionsconfigparserEverything is text; no lists
TOMLModern configuration with typestomllibRead-only in the standard library
pickleSaving Python objects between runspickleOnly for your own, trusted data
  • For hand-written configuration, TOML or INI; for exchange with other systems, JSON or XML; for saving your own objects, pickle (carefully).
  • XML and INI always return text: you have to convert numbers with int() or float().
  • Text formats can be opened and debugged with any editor; pickle cannot.

The exercises in this lesson practice each of them, for example From XML to dictionary and From TOML to JSON.