This module handles read and write operations to INI files, with data type preservation and support for nesting subsections to any depth.
Data to be written to INI must be stored in a dictionary with string keys. Data cannot be stored at the root level of the dictionary, it must be inside a sub-dictionary. This means that in the INI file, all parameters must be in a section, and if you need a default section you must define it explicitly.
Write a dictionary to an INI file:
from silx.io.configdict import ConfigDict
ddict = {
'simple_types': {
'float': 1.0,
'int': 1,
'string': 'Hello World',
},
'containers': {
'list': [-1, 'string', 3.0, False],
'array': numpy.array([1.0, 2.0, 3.0]),
'dict': {
'key1': 'Hello World',
'key2': 2.0,
}
}
}
ConfigDict(initdict=ddict).write("foo.ini")
Read an INI file into a dictionary like structure:
from silx.io.configdict import ConfigDict
confdict = ConfigDict()
confdict.read("foo.ini")
print("Available sections in INI file:")
print(confdict.keys())
for key in confdict:
for subkey in confdict[key]:
print("Section %s, parameter %s:" % (key, subkey))
print(confdict[key][subkey])
String class providing typecasting methods to parse values in a ConfigDict generated configuration file.
‘1’, ‘yes’, ‘true’ and ‘on’ are interpreted as True
‘0’, ‘no’, ‘false’ and ‘off’ are interpreted as False
Returns: | Boolean |
---|---|
Raise: | ValueError if conversion to bool failed |
Return string after replacing escaped commas \, with regular commas , and removing leading backslash.
Returns: | str(self) |
---|
Return a list or a numpy array.
Any string containing a comma (,) character will be interpreted as a list: for instance -1, Hello World, 3.0, or 2.0,
The format for numpy arrays is a blank space delimited list of values between square brackets: [ 1.3 2.2 3.1 ], or [ [ 1 2 3 ] [ 1 4 9 ] ]
Store configuration parameters as an ordered dictionary.
Parameters can be grouped into sections, by storing them as sub-dictionaries.
Keys must be strings. Values can be: integers, booleans, lists, numpy arrays, floats, strings.
Methods are provided to write a configuration file in a variant of INI format. A ConfigDict can load (or be initialized from) a list of files.
The main differences between files written/read by this class and standard ConfigParser files are:
- sections can be nested to any depth
- value types are guessed when the file is read back
- to prevent strings from being interpreted as lists, commas are escaped with a backslash (\,)
- strings may be prefixed with a leading backslash (\) to prevent conversion to numeric or boolean values
Parameters: |
|
---|