How to implement a conf file using Python


I need to implement a configuration file of those used in Linux / Unix, to be able to access from a Python application. For example, given the file.txt file that contains:

# Hora inicio
hora_ini 14:00
# Hora final

hora_fin 22:00

I need my Python application to search, for example, the%% tag% and retrieve the hora_fin string in a variable, I do not know if I explain myself well.

asked by Carl0701 10.02.2016 в 17:09

1 answer


You can use the module ConfigParser , but first you should change your configuration file a bit since ConfigParser works with sections.

Sample file example.conf :

hora_ini = 14:00
hora_fin = 22:00

With the sample file example.conf , your script could look like this:

import ConfigParser

config = ConfigParser.ConfigParser()'example.conf')
hora_ini = config.get('HORAS', 'hora_ini')
hora_fin = config.get('HORAS', 'hora_fin')
print hora_ini
print hora_fin

The result would be:


You have not specified the version of Python you are working with, the previous example works for Python 2.x, in Python 3.x the module is called configparser .


If at any time you try to do something similar for, say, a Web application, what you can use is python-dotenv .

With this library you could pass sensitive parameters such as the password of your database to a file .env and not expose them in the configuration scripts.

You simply create a text file .env with the parameters you want:

$ cat .env

Now, the variables in the .env file will be available as variables in the system environment. For example, you can pass this:

SECRET_KEY = '23a/&dl3u80=!)?jsl3'

To this:

SECRET_KEY = os.environ.get("SECRET_KEY")

Much safer.

answered by 10.02.2016 / 17:22