python-dotenv: load_dotenv, dotenv_values and .env Syntax Explained
How python-dotenv loads a .env file: load_dotenv vs dotenv_values, why existing variables win by default, ${VAR} expansion, quoting and multiline rules, and the dotenv CLI.
Quick answer:
pip install python-dotenv, then callload_dotenv()at the top of your program. It finds the nearest.envfile and copies its values intoos.environ, without overwriting variables that are already set unless you passoverride=True. If you want the values as a dictionary instead of in the environment, usedotenv_values().
python-dotenv is the standard way to read a .env file in Python. It is small, but a few of its defaults surprise people: a variable already set in your shell silently beats the file, $VAR is not expanded while ${VAR} is, and a value with a space and a # behaves differently from one without. This guide covers the library itself. For reading variables once they are loaded (os.environ vs os.getenv, type conversion, validation), see our Python environment variables guide.
Facts below come from the python-dotenv README, its parser source and its PyPI page, checked on November 27, 2026. The current release is 1.2.4 (October 1, 2026), and it requires Python 3.10 or newer.
Install
pip install python-dotenv
The package is called python-dotenv, but you import it as dotenv. If you also want the dotenv command-line tool, install the extra:
pip install "python-dotenv[cli]"
load_dotenv(): put the file into os.environ
import os
from dotenv import load_dotenv
load_dotenv() # reads .env and copies its values into os.environ
database_url = os.environ["DATABASE_URL"]
With no arguments, load_dotenv() looks for a .env file in the same directory as the script, and if there is none there, higher up the directory tree. You can also point it at a file:
load_dotenv(".env.local")
Existing variables win by default
This is the behaviour that causes most "my .env change does nothing" questions. By default load_dotenv() does not override a variable that is already in the environment. If you exported DATABASE_URL in your shell an hour ago, that value stays, whatever the file says.
load_dotenv() # shell and system variables win
load_dotenv(override=True) # the .env file wins
The default is the safer one for deployments: the value your host or CI sets is the one your app uses, and a stray .env file cannot replace it. Use override=True when the file must be the source of truth, for example in a test setup.
Switching it off
Setting PYTHON_DOTENV_DISABLED=1 stops load_dotenv() from loading any file or stream. That gives you one switch to make sure load_dotenv() never reads a .env file in production, without changing the code. dotenv_values() is not affected.
dotenv_values(): a dictionary, environment untouched
dotenv_values() parses the file and returns a dict. It does not touch os.environ.
from dotenv import dotenv_values
config = dotenv_values(".env")
# {'DATABASE_URL': 'postgresql://localhost/app', 'DEBUG': 'true'}
That makes layering several files explicit. The README's own example merges a shared file, a secrets file and the real environment, with later entries winning:
import os
from dotenv import dotenv_values
config = {
**dotenv_values(".env.shared"), # shared development variables
**dotenv_values(".env.secret"), # sensitive variables
**os.environ, # the real environment wins
}
Use load_dotenv() when libraries in your app read os.environ themselves. Use dotenv_values() when you want a config object you control, or several files merged in a fixed order.
One detail: a line with only a key and no = (just FOO) gives None in the dictionary. FOO= gives an empty string.
.env syntax rules python-dotenv follows
There is no formal .env standard. python-dotenv describes its format as "mostly" like a Bash file. The rules worth knowing:
# Comments start with #
DATABASE_URL=postgresql://localhost/app
DEBUG=true # after an unquoted value, a comment needs a space before the #
API_KEY='single quoted, taken literally'
GREETING="double quoted\nwith an escaped newline"
export PORT=8000 # python-dotenv ignores the export prefix
PRIVATE_KEY="-----BEGIN KEY-----
spans several lines
-----END KEY-----"
- Keys can be unquoted or single-quoted. Values can be unquoted, single-quoted or double-quoted.
- Spaces around the key, the
=and the value are ignored. - After an unquoted value,
#starts a comment only when whitespace comes before it, soPASSWORD=abc#123keeps the#. After a closing quote, a comment can follow directly. - Quoted values can span several lines, which is how certificates and private keys usually end up in a
.envfile. - In double quotes, escapes such as
\n,\tand\"work. In single quotes, only\\and\'do. - A leading
exportis ignored by python-dotenv.
Variable expansion: ${VAR} yes, $VAR no
python-dotenv expands variables POSIX-style, but only in braces:
DOMAIN=example.org
ADMIN_EMAIL=admin@${DOMAIN} # becomes admin@example.org
SUPPORT_EMAIL=help@$DOMAIN # stays help@$DOMAIN, not expanded
Where the value of ${DOMAIN} comes from depends on override:
| Call | Looks for the value in this order |
|---|---|
load_dotenv() (default, override=False) | the environment, then the .env file, then a default value, then an empty string |
load_dotenv(override=True) or dotenv_values() | the .env file, then the environment, then a default value, then an empty string |
If you need a literal ${...} in a value, pass interpolate=False to load_dotenv() or dotenv_values() to turn expansion off.
Loading from a stream instead of a file
Both functions accept a text stream through stream, which is handy in tests or when the configuration comes from somewhere other than disk:
from io import StringIO
from dotenv import load_dotenv
config = StringIO("USER=foo\nEMAIL=foo@example.org")
load_dotenv(stream=config)
The dotenv CLI
With the [cli] extra installed you get a dotenv command for working with the file from a terminal:
dotenv set USER foo # write a key to .env
dotenv get USER # print one value
dotenv list # print all keys and values
dotenv list --format=json
dotenv run -- python app.py # run a command with .env loaded into its environment
dotenv --help lists every option.
In Jupyter or IPython, %load_ext dotenv followed by %dotenv loads the nearest .env file into the kernel. Add -o to override existing variables.
Common mistakes
- Calling
load_dotenv()too late. If a module readsos.environat import time, the import must come afterload_dotenv(). Put the call at the very top of your entry point. - Expecting the file to beat your shell. It does not, unless you pass
override=True. - Writing
$VARinstead of${VAR}. Only the braced form is expanded. - Committing the file. A
.envfile holds real credentials. Add it to.gitignorebefore the first commit, and commit a.env.examplewith the keys and no values. Our guide to adding .env to .gitignore covers fixing a file that is already tracked.
Where the .env file comes from on a team
python-dotenv solves reading the file. It does not solve getting the right file onto five laptops and three servers, or knowing who changed STRIPE_KEY last week. That part usually ends up in a chat message.
EnvManager keeps a team's variables per project and environment, and the CLI writes them to the file python-dotenv reads:
envmanager pull # writes .env for the configured environment
envmanager pull --environment staging --output .env.staging
Your code stays the same: load_dotenv() or load_dotenv(".env.staging").
You can also skip the file. envmanager run starts your program with the variables you allow already in its environment:
envmanager run --only DATABASE_URL,SECRET_KEY -- python app.py
Because load_dotenv() does not override variables that are already set, the same load_dotenv() call still works locally with a file and stays out of the way when the values come from envmanager run or your host.
Stop sending .env files around
One flat price for the whole team, not per seat. Import your current .env file when you sign up.
FAQ
What is the difference between python-dotenv and dotenv?
python-dotenv is the name of the package on PyPI, so it is what you pip install. In code you import it as dotenv: from dotenv import load_dotenv.
Does load_dotenv() override existing environment variables?
No, not by default. Variables already in the environment keep their value. Pass override=True to let the .env file win.
How do I load a .env file from another directory?
Pass the path: load_dotenv("/path/to/.env") or dotenv_values("config/.env.local"). Without a path, load_dotenv() uses the .env next to the script, or the nearest one higher up the tree.
Should I use python-dotenv in production?
It works, but most hosts let you set environment variables directly, and with the default override=False those values win anyway. If you want to be sure load_dotenv() never reads a .env file in production, set PYTHON_DOTENV_DISABLED=1 there. It does not affect dotenv_values(), which still reads the file you point it at.