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

  1. Security – Keeps sensitive credentials out of source code by excluding .env in .gitignore
  2. Separation of Concerns – Separates configuration from code, enabling easy environment switching
  3. Collaboration – Team members use individual .env files without modifying shared code; .env.example documents requirements
  4. Convenience – No need to set OS-level environment variables repeatedly
  5. Portability – Facilitates containerization and deployment with Docker and CI/CD pipelines

Python .env Cheat Sheet

TaskCode Snippet
Install python-dotenvpip install python-dotenv
Load .env filefrom dotenv import load_dotenv; load_dotenv()
Access env variableos.getenv("VAR_NAME")
Set a default if missingos.getenv("VAR_NAME", "default")
Convert string to booleanos.getenv("DEBUG", "False") == "True"
Example variable in .envDEBUG=True
Ignore .env in GitAdd .env to .gitignore
Create a templateUse .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 .env file — add it to .gitignore
  • Use a .env.example file to document required environment variables
  • Regenerate and rotate secrets periodically
  • Use strong, random values for sensitive keys
  • Maintain separate .env files 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.