Common Configuration File Formats and Their Python Parsing Methods
This article introduces the most popular configuration file formats—INI, JSON, TOML, and YAML—explains their structures, compares their advantages and drawbacks, and provides Python code examples for reading each format using built‑in or third‑party libraries.
During development, fixed parameters are often stored in a dedicated configuration file to keep core code clean; while a simple .py file works within a single Python project, cross‑language projects benefit from universal formats such as INI, JSON, TOML, and YAML.
INI files consist of sections, keys, and values. Python’s built‑in configparser can read them directly. Example:
[localdb]
host = 127.0.0.1
user = root
password = 123456
port = 3306
database = mysqlParsing with configparser :
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read("/Users/Bobot/db.ini")
print(cfg.items("localdb"))JSON is a widely used data‑exchange format that can also serve as a configuration file. Python’s json module provides load() and loads() for reading JSON data.
{
"localdb": {
"host": "127.0.0.1",
"user": "root",
"password": "123456",
"port": 3306,
"database": "mysql"
}
}Reading the file:
import json
from pprint import pprint
with open('/Users/Bobot/db.json') as j:
cfg = json.load(j)['localdb']
pprint(cfg)TOML was created by Tom Preston‑Werner and offers a richer syntax than INI while remaining easy to read. Install the third‑party toml package via pip install toml . Example configuration:
[mysql]
host = "127.0.0.1"
user = "root"
port = 3306
database = "test"
[mysql.parameters]
pool_size = 5
charset = "utf8"
[mysql.fields]
pandas_cols = ["id", "name", "age", "date"]Parsing with toml :
import toml, os, pprint
cfg = toml.load(os.path.expanduser("~/Desktop/config.toml"))
pprint(cfg)YAML is a highly expressive format popular in DevOps (e.g., Docker Compose). Install pyyaml via pip install pyyaml . Because yaml.load() can execute arbitrary code, use yaml.safe_load() for security.
# Dangerous example (do NOT run)
!!python/object/apply:os.system ["rm -rf /"]Reading a YAML file safely:
import yaml, os, pprint
with open(os.path.expanduser("~/config.yaml"), "r") as f:
cfg = yaml.safe_load(f)
pprint(cfg)In summary, the complexity of these formats increases roughly as INI < JSON ≈ TOML < YAML; each has its own trade‑offs, and the choice should depend on project requirements, team preferences, and security considerations.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.