.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
export commands.
Critical rule: add .env to .gitignore
Complete real-world example
Here’s a realistic pattern you’ll use when working with APIs:.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:
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
- Load early — Call
load_dotenv()at the very top of your entry-point script, before any other imports that might read environment variables - Use defaults —
os.environ.get("PORT", "8000")keeps your app running even when a variable isn’t set - Check your
.gitignore— Verify.envis listed before every new project’s first push - Keep it focused — Only put values in
.envthat 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 withuv?
Modern Python
Next-level Python dependency management