In this section, we are going learn about the configparser module of Python. By using the configparser module, you can manage user-editable configuration files for the application.
The common use of these configuration files is that users or system administrators can edit the files using a simple text editor to set application defaults and then the application will read and, parse them and act based on the contents written in them.
To read a configuration file, configparser has the read() method. Now, we will write a simple script named read_config_file.py. Before that, create a .ini file named read_simple.ini and write the following content in it: read_simple.ini
[bug_tracker]
url = https://timesofindia.indiatimes.com/
Create read_config_file.py and enter the following content in it:
from configparser import ConfigParser
p = ConfigParser()
p.read('read_simple.ini')
print(p.get('bug_tracker', 'url'))
Run read_config_file.py and you will get the following output:
$ python3 read_config_file.py
Output:
https://timesofindia.indiatimes.com/
The read() method accepts more than one filename. Whenever each filename gets scanned and if that file exists, then it will be opened and read. Now, we will write a script for reading more than one filename. Create a script called read_many_config_file.py and write the following code in it:
from configparser import ConfigParser
import glob
p = ConfigParser()
files = ['hello.ini', 'bye.ini', 'read_simple.ini', 'welcome.ini']
files_found = p.read(files)
files_missing = set(files) - set(files_found)
print('Files found: ', sorted(files_found))
print('Files missing: ', sorted(files_missing))
Run the preceding script and you will get the following output:
$ python3 read_many_config_file.py
Output
Files found: ['read_simple.ini']
Files missing: ['bye.ini', 'hello.ini', 'welcome.ini']
In the preceding example, we used the configparser module of Python, which helps in managing configuration files. First, we created a list named files. The read() function will read the configuration files. In the example, we created a variable called files_found, which will store the names of the configuration files present in your directory. Next, we created another variable called files_missing, which will return filenames that aren't in your directory. And, lastly, we are printing the file names that are present and missing.