What Is a .env File?
A .env file (environment file) stores key-value pairs that configure application behavior externally from source code. These variables can include API keys, database credentials, secret tokens, debug modes, and email settings.
This approach separates configuration from code and can reduce accidental exposure when the file is excluded from version control. A .env file is not a security boundary, so protect its permissions and use a dedicated secrets manager for production systems when appropriate.
Common .env file contents:
- Database credentials
- Secret API keys
- Debug flags
- Server ports
- Email credentials
Example .env file:
DEBUG=True
SECRET_KEY=your-secret-key
DATABASE_URL=mysql://user:password@localhost/dbname
API_KEY=123456789abcdef
The values above are placeholders. Never commit real credentials to a repository, even in an example file.
How It Works
Install the python-dotenv package:
pip install python-dotenv
Load the .env file in your Python application:
from dotenv import load_dotenv
import os
load_dotenv() # Loads variables from .env into environment
# Now you can access the variables using os.getenv
secret_key = os.getenv("SECRET_KEY")
debug_mode = os.getenv("DEBUG", "False") == "True"
Benefits of Using a .env File
- Security – Keeps sensitive credentials out of source code by excluding
.envin.gitignore - Separation of Concerns – Separates configuration from code, enabling easy environment switching
- Collaboration – Team members use individual
.envfiles without modifying shared code;.env.exampledocuments requirements - Convenience – No need to set OS-level environment variables repeatedly
- Portability – Facilitates containerization and deployment with Docker and CI/CD pipelines
Python .env Cheat Sheet
| Task | Code Snippet |
|---|---|
Install python-dotenv | pip install python-dotenv |
Load .env file | from dotenv import load_dotenv; load_dotenv() |
| Access env variable | os.getenv("VAR_NAME") |
| Set a default if missing | os.getenv("VAR_NAME", "default") |
| Convert string to boolean | os.getenv("DEBUG", "False") == "True" |
Example variable in .env | DEBUG=True |
Ignore .env in Git | Add .env to .gitignore |
| Create a template | Use .env.example with placeholder values |
| Manually set env (alt method) | export VAR_NAME=value (Linux/macOS), set VAR_NAME=value (Windows) |
Best Practices for .env files
- Never commit your
.envfile — add it to.gitignore - Use a
.env.examplefile to document required environment variables - Regenerate and rotate secrets periodically
- Use strong, random values for sensitive keys
- Maintain separate
.envfiles for different environments (development, staging, production) - Validate required environment variables at runtime
In Conclusion
.env files are a convenient way to manage local configuration. By externalizing configuration and handling secrets carefully, developers can reduce accidental exposure, reduce errors, and support multiple environments.
