Skip to main content
A .env file is a plain text file that lives in your project root and holds all of your environment variables in one place. Instead of typing export commands every time you open a terminal, you write your configuration values once and let the python-dotenv library load them automatically at the start of your program. This approach is standard across the Python ecosystem — you’ll see it in FastAPI projects, data science notebooks, and production services alike.

Basic setup

1

Install python-dotenv

2

Create your .env file

Create a file named .env in your project root. No extension — just .env:
3

Load it in Python

That’s all there is to it. Much easier than managing export commands.

Critical rule: add .env to .gitignore

Never commit your .env file. It contains real secrets. Add it to .gitignore before your very first commit — once a secret is in your Git history, it’s there forever even if you delete the file later.

Complete real-world example

Here’s a realistic pattern you’ll use when working with APIs:
Your .env file for this project:

Show others what variables they need

Create a companion file called .env.example — this one you do commit to Git:
This file documents exactly what variables a new contributor needs to set up, without exposing any real values. It’s a standard convention in open-source Python projects.

Rules for .env files

  • One variable per line
  • No spaces around =
  • No quotes (unless the value itself contains spaces)
  • Use # for comments
  • Names should be UPPERCASE

Common patterns

Quick tips

  1. Load early — Call load_dotenv() at the very top of your entry-point script, before any other imports that might read environment variables
  2. Use defaultsos.environ.get("PORT", "8000") keeps your app running even when a variable isn’t set
  3. Check your .gitignore — Verify .env is listed before every new project’s first push
  4. Keep it focused — Only put values in .env that genuinely change between environments or need to stay secret

What’s next?

You now know how to manage secrets safely. Ready for modern Python tooling with uv?

Modern Python

Next-level Python dependency management