Read environment variables from file in Python
A .env file is a text file containing key value pairs of environment variables. This file is normally included with a project, but not committed to source.
How to read .env files using Python
Firstly, install the dotenv package.
1pip install python-dotenvInclude the folllowing lines:
1from dotenv import load_dotenv
2
3load_dotenv()Using load_dotenv(), the application will load the .env file and host environment variables. If this is the .env file for the application:
1VARIABLE1=testThen the output will be test for the following snippet:
1from dotenv import load_dotenv
2import os
3
4load_dotenv()
5
6print(os.environ.get("VARIABLE1")) # outputs testHowever, if the host environment has a VARIABLE1 defined:
1export VARIABLE1=test2The output will change to test2.
If this is not desired behavior, the author may opt to use dotenv_values which returns a dict of values strictly parsed from the .env file:
1from dotenv import dotenv_values
2
3config = dotenv_values()
4print(config) # outputs OrderedDict([('VARIABLE1', 'test')])If the .env file resides on a different path than the default root directy of the project, use the dotenv_path option:
1from dotenv import load_dotenv
2from pathlib import Path
3
4load_dotenv(dotenv_path=Path("path/to/file"))