Skip to main content

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

That’s it! Much easier than export commands.

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:
Your .env file:

Show others what they need

Create .env.example (this one you DO commit):
This shows other developers what variables they need without exposing your actual keys.

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

  1. Load early: Put load_dotenv() at the start of your program
  2. Use defaults: os.environ.get('PORT', '8000')
  3. Check your .gitignore: Make sure .env is listed
  4. 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