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.
Python code
21 linesimport 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
[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
- Use `config.read('example.ini')` to load an existing INI file instead of writing
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.