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.
|
|
Include the folllowing lines:
|
|
Using load_dotenv()
, the application will load the .env
file and host environment variables. If this is the .env
file for the application:
|
|
Then the output will be test
for the following snippet:
|
|
However, if the host environment has a VARIABLE1
defined:
|
|
The 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:
|
|
If the .env
file resides on a different path than the default root directy of the project, use the dotenv_path
option:
|
|