I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file.
I run into Python's ConfigParser and I wondered if the INI file format is really still appropriate nowadays?! Does there exist a more up-to-date format or is INI still the recommended way to go? (XML, JSON, ...)
Please share your opinions/recommendations...
Python can have config files with all settings needed by the application dynamically or periodically. Python config files have the extension as . ini. We'll use VS Code (Visual Studio Code) to create a main method that uses config file to read the configurations and then print on the console.
To read and write INI files, we can use the configparser module. This module is a part of Python's standard library and is built for managing INI files found in Microsoft Windows. This module has a class ConfigParser containing all the utilities to play around with INI files.
The python's configparser module used to read the . ini files, typically these file contains configuration information. The following few examples illustrate some of the more interesting features of the ConfigParser module.
Consider using plain Python files as configuration files.
An example (config.py
):
# use normal python comments value1 = 32 value2 = "A string value" value3 = ["lists", "are", "handy"] value4 = {"and": "so", "are": "dictionaries"}
In your program, load the config file using exec
(docs):
from pathlib import Path if __name__ == "__main__": config = {} exec(Path("config.py").read_text(encoding="utf8"), {}, config) print(config["value1"]) print(config["value4"])
I like this approach, for the following reasons:
The approach is widely used, a few examples:
execfile
, it uses import
to read/execute settings.py
AFAIK, but the end result is the same: the code inside the settings file is executed.~/.bashrc
on startup.site.py
on startup.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With