What is a .env file?
A.env file is a simple text file that stores your environment variables. Instead of typing export commands, you write them once in a file.
Basic setup
1. Install python-dotenv
2. Create .env file
Create a file named.env in your project:
3. Load in Python
Critical: Add to .gitignore
Never commit .env files! They contain secrets. Add to
.gitignore immediately:Complete example
Here’s a real example with an API:.env file:
Show others what they need
Create.env.example (this one you DO commit):
Rules for .env files
- One variable per line
- No spaces around
= - No quotes (unless part of the value)
- Use
#for comments - Always UPPERCASE names
Common patterns
Quick tips
- Load early: Put
load_dotenv()at the start of your program - Use defaults:
os.environ.get('PORT', '8000') - Check your .gitignore: Make sure
.envis listed - Keep it simple: Only put configuration that changes
What’s next?
You now know how to manage secrets safely! Ready for modern Python tooling?Modern Python
Next-level Python development