How to read and write an INI file with Python3?

I need to read, write and create an INI file with Python3.

FILE.INI

default_path = "/path/name/" default_file = "file.txt" 

Python file:

 # read file and if not exists ini = iniFile( 'FILE.INI' ) # Get and Print Config Line "default_path" getLine = ini.default_path # Print (string)/path/name print getLine # Append new line and if exists edit this line ini.append( 'default_path' , 'var/shared/' ) ini.append( 'default_message' , 'Hey! help me!!' ) 

UPDATE FILE.INI

 default_path = "var/shared/" default_file = "file.txt" default_message = "Hey! help me!!" 
+57
python ini
Jan 16 2018-12-12T00:
source share
5 answers

This could be where to start:

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

Further information can be found in the official documentation.

+87
Jan 16 '12 at 18:34
source share

Here is a complete example of reading, updating, and writing.

Input file, test.ini

 [section_a] string_val = hello bool_val = false int_val = 11 pi_val = 3.14 

Working code.

 try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # ver. < 3.0 # instantiate config = ConfigParser() # parse existing file config.read('test.ini') # read values from a section string_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 value config.set('section_a', 'string_val', 'world') # add a new section and some values config.add_section('section_b') config.set('section_b', 'meal_val', 'spam') config.set('section_b', 'not_found_val', 404) # save to a file with open('test_update.ini', 'w') as configfile: config.write(configfile) 

Output file, test_update.ini

 [section_a] string_val = world bool_val = false int_val = 11 pi_val = 3.14 [section_b] meal_val = spam not_found_val = 404 

The original input file remains untouched.

+33
Apr 6 '15 at 20:55
source share

http://docs.python.org/library/configparser.html

In this case, the standard Python library may be useful.

+8
Jan 16 '12 at 18:03
source share

The ConfigParser standard usually requires access through config['section_name']['key'] , which is easy. A small modification may provide access to attributes:

 class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self 

AttrDict is a class derived from dict that provides access through dictionary keys and attribute access: this means ax is a['x']

We can use this class in ConfigParser :

 config = configparser.ConfigParser(dict_type=AttrDict) config.read('application.ini') 

and now get application.ini with:

 [general] key = value 

but

 >>> config._sections.general.key 'value' 
+3
Apr 28 '15 at 16:56
source share

ConfigObj is a good alternative to ConfigParser, which offers much more flexibility:

  • Nested sections (subsections) at any level
  • List Values
  • Multiple String Values
  • String interpolation (wildcard)
  • Integrated with a powerful validation system, including automatic verification / conversion of repeat partition types and resolution of default values
  • When writing configuration files, ConfigObj saves all comments and the order of members and sections
  • Many useful methods and features for working with configuration files (for example, the reload method)
  • Full Unicode Support

It has a flip side:

  • You cannot set a separator, it must be = ... ( pull request )
  • You cannot have empty values, well you can, but they look to be your favorite: fuabr = instead of just fubar , which looks weird and wrong.
+2
Sep 02 '16 at 7:44
source share



All Articles