Search code examples
pythonenvironment-variablespython-os

Python: Get value of env variable from a specific .env file


In python, is there a way to retrieve the value of an env variable from a specific .env file? For example, I have multiple .env files as follows:

.env.a .env.a ...

And I have a variable in .env.b called INDEX=4.

I tried receiving the value of INDEX by doing the following:

import os

os.getenv('INDEX')

But this value returns None.

Any suggestions?


Solution

  • This is a job for ConfigParser or ConfigObj. ConfigParser is built into the Python standard library, but has the drawback that it REALLY wants section names. Below is for Python3. If you're still using Python2, then use import ConfigParser

    import configparser
    config = configparser.ConfigParser()
    config.read('env.b')
    index = config['mysection']['INDEX']
    

    where env.b for ConfigParser is

    [mysection]
    INDEX=4
    

    And using ConfigObj:

    import configobj
    config = configobj.ConfigObj('env.b')
    index = config['INDEX']
    

    where env.b for ConfigObj is

    INDEX=4