How to read and write INI file with Python3?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python's built-in configparser module reads and writes INI files without any external dependencies. To read: create a ConfigParser instance, call config.read('file.ini'), then access values with config['section']['key']. To write: set values on the ConfigParser object and call config.write(open('file.ini', 'w')). The module handles sections, key-value pairs, defaults, interpolation, and type conversion out of the box.
INI File Structure
Sections are enclosed in [], keys use = or : as delimiters, and comments start with ; or #.
Reading an INI File
Type Conversion
All values are stored as strings. Use typed getters for conversion:
Writing an INI File
Modifying an Existing File
Interpolation (Variable Substitution)
configparser supports referencing other values within the same section or DEFAULT:
Reading from a String
Real-World Example
Common Pitfalls
- All values are strings:
config['server']['port']returns'8080'(a string), not8080. Usegetint(),getfloat(), orgetboolean()for typed values. Passing the string directly to code expecting an integer causesTypeError. - DEFAULT section bleeds into all sections: Keys in
[DEFAULT]appear in every section when iterating withconfig['section'].items(). This is by design — DEFAULT provides fallback values. If you want section-specific keys only, checkconfig.options('section')and filter out DEFAULT keys. - Case-insensitive keys by default:
configparserlowercases all keys.config['DB']['Host']andconfig['DB']['host']are the same. To preserve case, setconfig.optionxform = strbefore reading. read()silently ignores missing files:config.read('nonexistent.ini')returns an empty list and does not raise an error. Check the return value or useconfig.read_file(open('file.ini'))which raisesFileNotFoundErrorif the file does not exist.- Multi-line values need indentation: To store multi-line values, indent continuation lines with whitespace. Unindented lines are treated as new keys, causing
MissingSectionHeaderErroror corrupted data.
Summary
- Use
configparser.ConfigParser()withread(),get(), andwrite()for INI file operations - Use
getint(),getfloat(),getboolean()for type-safe value retrieval with optionalfallbackdefaults - The
[DEFAULT]section provides fallback values inherited by all sections - Use
%(key)sfor basic interpolation orExtendedInterpolationfor cross-section references - Always open the file with
'w'mode when writing —config.write()outputs the entire configuration
Related reading
- How to read binary files in Python using NumPy?
- How to read data from numpy files in TensorFlow?
- How to read data in Google Colab from my Google drive?
- How to read data into Tensorflow?
- How to read first N lines of a file?
- How to read the RGB value of a given pixel in Python?
- How to redirect 'print' output to a file?
- How to redirect TensorFlow logging to a file?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.