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}
| Format | Best for | Module | Notes |
|---|---|---|---|
| CSV | Tables of rows and columns | csv | No types: everything is text |
| JSON | Exchange between programs and APIs | json | Lists, dictionaries, numbers, text |
| XML | Structured documents with attributes | xml.etree.ElementTree | Verbose; common in older systems |
| INI | Simple configuration in sections | configparser | Everything is text; no lists |
| TOML | Modern configuration with types | tomllib | Read-only in the standard library |
| pickle | Saving Python objects between runs | pickle | Only 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()orfloat(). - 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.