Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Using python-dotenv to Load Environment Variables from .env

Learn how to use python-dotenv to load environment variables from .env files, including installation, load_dotenv, override behavior, dotenv_values, security, and common mistakes.

~3 min readPython
#python-dotenv#environment variables#configuration#secrets management
Illustration of a Python script loading environment variables from a .env file into a process.

Loading environment variables from a .env file is a common requirement in Python projects. python-dotenv reads KEY=VALUE pairs from the file and exposes them through os.environ, which makes it the standard tool for this task. This article covers installation, the main loading functions, override behavior, security, and common mistakes.

Installing python-dotenv

Install the package with pip:

bash
pip install python-dotenv

If you use Poetry or pipenv, add it as a regular dependency. For development-only use, you can mark it as a dev dependency, but many projects include it in production because the .env file may be used in deployment environments.

Loading the .env File with load_dotenv

The most common function is load_dotenv(). By default, it looks for a file named .env in the current working directory and loads its contents into the environment.

python
from dotenv import load_dotenv import os load_dotenv() db_host = os.getenv('DB_HOST') print(db_host)

load_dotenv() does not overwrite existing environment variables by default. If a variable is already set in the process environment, the value from .env is ignored. To override existing values, pass override=True:

python
load_dotenv(override=True)

This is useful in local development when you want the .env file to take precedence over variables set in your shell.

Understanding the Override Behavior

The default behavior prevents .env from masking real environment variables, which is important in production where you might have variables set by the deployment system. For example, if DB_HOST is already set in the environment, load_dotenv() will not change it. This avoids accidental overrides that could break the application.

If you need to force the .env values to take effect, use override=True. However, be cautious: this can hide configuration errors if the .env file contains stale or incorrect values.

Using dotenv_values for Dictionary Access

Sometimes you don't want to modify the process environment. The dotenv_values() function returns a dictionary of the parsed .env file without touching os.environ.

python
from dotenv import dotenv_values config = dotenv_values('.env') print(config.get('API_KEY'))

This is useful for configuration loading where you want to merge values from different sources or validate them before applying. It also avoids side effects on the global environment.

Handling Missing or Invalid .env Files

load_dotenv() returns False if the file is not found, but it does not raise an exception. This can be problematic if the .env file is required for the application to run. You can explicitly check the return value:

python
from dotenv import load_dotenv if not load_dotenv(): raise RuntimeError('Missing .env file')

Malformed lines that do not follow the KEY=VALUE format are ignored by the parser rather than causing an exception. The library does not provide a strict parser, so it is your responsibility to ensure the file is correctly formatted and to validate required keys after loading if you want to fail fast.

Security Considerations for .env Files

.env files often contain secrets like API keys, database credentials, and tokens. It is critical to keep them out of version control. Add .env to your .gitignore file:

gitignore
.env

For production, consider using a secret management service instead of a .env file. If you do use .env in production, ensure the file permissions are restricted (for example, chmod 600). If you commit a .env.example file, keep real values out of it and use placeholders.

Integration with Configuration Libraries

python-dotenv can be combined with configuration libraries like pydantic or dynaconf. For example, with pydantic v2, install pydantic-settings and use BaseSettings from pydantic_settings:

python
from pydantic_settings import BaseSettings from dotenv import load_dotenv load_dotenv() class Settings(BaseSettings): database_url: str api_key: str settings = Settings()

This pattern loads the .env file first, then lets the configuration library read from the environment. It keeps your configuration logic separate from environment loading.

Common Mistakes and How to Avoid Them

One common mistake is calling load_dotenv() after importing modules that read environment variables at import time. Environment variables are read at runtime, so the call must happen before any code that depends on them. For example:

python
import os from dotenv import load_dotenv load_dotenv() # Now safe to read env vars value = os.getenv('VALUE')

Another mistake is using relative paths for the .env file. load_dotenv() looks in the current working directory, which may not be the project root when running scripts from elsewhere. Use find_dotenv() to locate the file relative to the script:

python
from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv())

find_dotenv() searches upward from the calling file to find a .env file, making your script location-independent.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.