How to read and write INI file with Python3? How to read and write INI file with Python3? python python

How to read and write INI file with Python3?


This can be something to start with:

import configparserconfig = configparser.ConfigParser()config.read('FILE.INI')print(config['DEFAULT']['path'])     # -> "/path/name/"config['DEFAULT']['path'] = '/var/shared/'    # updateconfig['DEFAULT']['default_message'] = 'Hey! help me!!'   # createwith open('FILE.INI', 'w') as configfile:    # save    config.write(configfile)

You can find more at the official configparser documentation.


Here's a complete read, update and write example.

Input file, test.ini

[section_a]string_val = hellobool_val = falseint_val = 11pi_val = 3.14

Working code.

try:    from configparser import ConfigParserexcept ImportError:    from ConfigParser import ConfigParser  # ver. < 3.0# instantiateconfig = ConfigParser()# parse existing fileconfig.read('test.ini')# read values from a sectionstring_val = config.get('section_a', 'string_val')bool_val = config.getboolean('section_a', 'bool_val')int_val = config.getint('section_a', 'int_val')float_val = config.getfloat('section_a', 'pi_val')# update existing valueconfig.set('section_a', 'string_val', 'world')# add a new section and some valuesconfig.add_section('section_b')config.set('section_b', 'meal_val', 'spam')config.set('section_b', 'not_found_val', '404')# save to a filewith open('test_update.ini', 'w') as configfile:    config.write(configfile)

Output file, test_update.ini

[section_a]string_val = worldbool_val = falseint_val = 11pi_val = 3.14[section_b]meal_val = spamnot_found_val = 404

The original input file remains untouched.