Python configuration files
There are several ways to do this, depending on the desired file format.
ConfigParser [.ini format]
I would use standard configparser if there was no good reason to use a different format.
Write a file like this:
from ConfigParser import SafeConfigParser config = SafeConfigParser() config.read('config.ini') config.add_section('main') config.set('main', 'key1', 'value1') config.set('main', 'key2', 'value2') config.set('main', 'key3', 'value3') with open('config.ini', 'w') as f: config.write(f)
The file format is very simple with sections highlighted in square brackets:
[main] key1 = value1 key2 = value2 key3 = value3
Values ββcan be extracted from the file as follows:
from ConfigParser import SafeConfigParser config = SafeConfigParser() config.read('config.ini') print config.get('main', 'key1')
JSON [.json format]
JSON data can be very complex and have the advantage of being very portable.
Writing data to a file:
import json config = {'key1': 'value1', 'key2': 'value2'} with open('config.json', 'w') as f: json.dump(config, f)
Reading data from a file:
import json with open('config.json', 'r') as f: config = json.load(f)
Yaml
A basic YAML example is provided in this answer . More information can be found on the pyYAML website .
Graeme Stuart Sep 29 '13 at 13:42 on 2013-09-29 13:42
source share