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
:
[HORAS]
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()
config.read('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:
14:00
22:00
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
.
Bonus
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
SECRET_KEY="23a/&dl3u80=!)?jsl3"
DATABASE_PASSWORD="12345"
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'
DATABASE_PASSWORD = '12345'
To this:
SECRET_KEY = os.environ.get("SECRET_KEY")
DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
Much safer.