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

Viewed 8988

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?

2 Answers

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

Python has a specific package named python-dotenv to use keys stored in the .env file. Here is how we can use a key in the .env file. First, create a key like this in the .env file

demokey=aaa2134

To load this key in the python file we can use this code:

from dotenv import load_dotenv
load_dotenv()
import os
x = os.getenv("demokey")
print(x)

In Python 3.x , since its not available natively

pip install python-dotenv
Related