dotenv in Python

dotenv in Python

Shivam Arora Oct-02, 2021 Sep-22, 2021 Python Python Environment

This article will explain the meaning and the use of dotenv in Python.

The .env file is an individual file containing the key values described above for all environmental variables needed in your application. The file is stored locally without being saved to source control, so you are not putting potentially sensitive information at risk.

The dotenv is used to read the key and value pair from the .env file and add it to the environment variable. We can use it to manage the application settings during development and production phases by using its 12-factor principle.

The environment variables are established in a UNIX-like file inside the Python project directory using the env module.

To get started with the .env file, we first need to install the dotenv library.

pip install python-dotenv

Using dotenv, our application can load the configuration from a .env file when present (for example, during development) while retaining the environment-based configuration.

See the following example.

from dotenv import load_dotenv
config = load_dotenv(".env")

In the above example, we use the load_dotenv() function. The dotenv_values() function works similarly to the load_dotenv. It returns a dictionary with values parsed from the environment.

For example,

from dotenv import dotenv_values
config = dotenv_values(".env") 

We can also load the environment variables from a network rather than a file system. For this, we can use the StringIO() function from the io package to create a stream object.

See the following code.

from io import StringIO
from dotenv import load_dotenv

config = StringIO("USER=abc\")

We can also use the CLI interface dotenv to manipulate the .env file without opening it manually.

See the commands below.

pip install "python-dotenv[cli]"
dotenv set USER abc
dotenv set EMAIL
dotenv run -- python

Related Article - Python Environment

  • Access Environment Variables in Python
  • Get Environment Variables in Python
  • Read Environment Variables From Env File in Python
  • Set Environment Variables in Python
  • Set and Get Environment Variables in Python