How to write an INI config section with configparser in Python

Create an INI configuration file with sections using Python's configparser module and write it to disk.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

21 lines
Python 3.9+
import configparser

config = configparser.ConfigParser()
config["General"] = {
    "host": "localhost",
    "port": "8080",
    "debug": "true"
}
config["Database"] = {
    "name": "appdb",
    "user": "admin",
    "password": "secret"
}

with open("example.ini", "w") as file:
    config.write(file)

with open("example.ini") as file:
    content = file.read()

print(content)

Output

stdout
[General]
host = localhost
port = 8080
debug = true

[Database]
name = appdb
user = admin
password = secret

How it works

The configparser.ConfigParser() object manages configuration data in a structured way. Assigning dictionaries to section names creates or updates those sections. The config.write(file) method writes the configuration to a file in INI format, with each section and key-value pair on separate lines. Reading the file afterwards displays the exact content written. This approach is ideal for handling configuration settings in a readable, portable format.

Common mistakes

  • Forgetting to close the file when writing manually instead of using 'with'
  • Assuming values are typed; configparser stores everything as strings
  • Using 'true' instead of 'True' may cause issues if you later parse boolean values

Variations

  1. Use `config.read('example.ini')` to load an existing INI file instead of writing
  2. Add comments to sections using `config.set('General', '# comment', None)`

Real-world use cases

  • Generating configuration files for services at deployment time in CI pipelines.
  • Creating user-editable app settings that are easy to manage in plain text.
  • Storing database connection parameters for local development environments.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.