Introduction – Python programming language
The Python language is a high-level, interpreted, oriented language to objects with dynamic semantics. Its high-level structures, combined with its dynamic mooring typing makes it very attractive for the development of large applications as well as for use as scripting language or collage. In addition, simple Python syntax encourages reuse of code simplifying the maintenance and standardization of data in modules and packages.
Config files in Python
A good practice in software development is to make some parts configurable by users or even by developers, without the need to compile each change made in these configurations. This can be done through plain text files, easy to understand and can have their versions controlled in the configuration of programs.
While this is not the best way to describe something, the .INI files still exist in large numbers, precisely because of its simplicity and ease of use and maintenance.
Who ever saw or needed your program to read a file similar to the following?
[section1] config1=100 config2=0 [section2] confign=-1
These configuration files have several sections, each section representing a specific configuration for the program, which can contain several properties represented by a pair (key, value).
As much as we want to avoid such files, because they are even considered an obsolete format, sometimes it is necessary to read such a file to obtain information for our program. How to do this in Python? Read the file line by line? No! Let’s use the ConfigParser module.
First, we must import the module, instantiate a ConfigParser object and read the desired configuration file (in our case, config.ini):
import ConfigParser cfg = ConfigParser.ConfigParser() cfg.read('config.ini')
After that, the configuration file is already read, now it is enough that we get the values that we want to extract from the file. To get a file value, you need to specify the section and property that you want to get. For example, the code below gets the value of the confign property of section section2 and stores it in the variable x:
x = cfg.getint('section2', 'confign')
See that we use a method called getint () to read an integer value from the .INI file. If the data to be read was of another type, we could use one of the following methods: getboolean(), getfloat(), or simply get() in the case of strings.
With the same module, it is also possible to write .ini files.
As you can see, it is very simple to read these files, which despite being considered by many to be obsolete nowadays, still have vast applicability in software development, precisely because they have simplicity and practicality of use.