Python and .env Files

 

By default, Python does not automatically read environment variables from a .env file. The interpreter only accesses environment variables already set in the operating system. If you want Python to load variables from a .env file, you need to explicitly use a library such as python-dotenv to handle this process.

A .env file is typically used to store sensitive configuration values like API keys, database credentials, or environment-specific settings. This keeps them out of your source code and allows easy switching between environments.

Example workflow using python-dotenv:

# Install the library first:
# pip install python-dotenv

import os
from dotenv import load_dotenv

# Load variables from .env in the current directory
load_dotenv()

# Retrieve environment variables
db_host = os.getenv("DB_HOST", "localhost")
api_key = os.getenv("API_KEY")

print(f"Database Host: {db_host}")
print(f"API Key: {api_key}")

Steps to implement:

  • Install python-dotenv with pip install python-dotenv.

  • Create a .env file in your project root:

DB_HOST=127.0.0.1
API_KEY=your_api_key_here
  • Load it in your Python code using load_dotenv().

  • Access variables via os.getenv() or os.environ.get().

Best practices:

  • Never commit .env files to version control; add them to .gitignore.

  • Maintain a .env.example template with placeholder values for team members.

  • Use different .env files for development, testing, and production to simplify environment switching.

Key takeaway: Without python-dotenv or similar tools, Python will not read .env files automatically. You must explicitly load them into the environment before use, ensuring both security and flexibility in configuration management.

posted on 2026-06-17 15:18  漫思  阅读(6)  评论(0)    收藏  举报

导航