🔍 Code Extractor

function load_env_file

Maturity: 48

Reads and parses environment variables from a .env file in the current directory, returning them as a dictionary.

File:
/tf/active/vicechatdev/SPFCsync/validate_config.py
Lines:
58 - 77
Complexity:
simple

Purpose

This function provides a simple mechanism to load environment variables from a .env file without requiring external libraries like python-dotenv. It reads the file line by line, parses key-value pairs separated by '=', ignores comments (lines starting with '#') and empty lines, and returns a dictionary of environment variables. If the file doesn't exist or an error occurs during reading, it prints an error message and returns None.

Source Code

def load_env_file():
    """Load environment variables from .env file."""
    env_vars = {}
    env_path = ".env"
    
    if not os.path.exists(env_path):
        print("❌ .env file not found. Please create it from .env.example")
        return None
    
    try:
        with open(env_path, 'r') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    env_vars[key.strip()] = value.strip()
        return env_vars
    except Exception as e:
        print(f"❌ Error reading .env file: {e}")
        return None

Return Value

Returns a dictionary (dict) where keys are environment variable names (strings) and values are their corresponding values (strings), both stripped of whitespace. Returns None if the .env file doesn't exist or if an error occurs during file reading. The dictionary will be empty if the file exists but contains no valid key-value pairs.

Required Imports

import os

Usage Example

# Create a .env file first with content like:
# API_KEY=your_api_key_here
# DATABASE_URL=postgresql://localhost/mydb
# DEBUG=True

import os

def load_env_file():
    """Load environment variables from .env file."""
    env_vars = {}
    env_path = ".env"
    
    if not os.path.exists(env_path):
        print("❌ .env file not found. Please create it from .env.example")
        return None
    
    try:
        with open(env_path, 'r') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    env_vars[key.strip()] = value.strip()
        return env_vars
    except Exception as e:
        print(f"❌ Error reading .env file: {e}")
        return None

# Usage
env_vars = load_env_file()
if env_vars:
    api_key = env_vars.get('API_KEY')
    database_url = env_vars.get('DATABASE_URL')
    print(f"Loaded {len(env_vars)} environment variables")
else:
    print("Failed to load environment variables")

Best Practices

  • Always check if the returned value is None before attempting to access environment variables
  • The function uses split('=', 1) to handle values that contain '=' characters correctly
  • Empty lines and comments (lines starting with '#') are automatically ignored
  • The function does not set os.environ variables; it only returns a dictionary - you must manually set them if needed
  • Consider adding the .env file to .gitignore to avoid committing sensitive credentials
  • The function reads from the current working directory; ensure the script is run from the correct location or modify env_path to use an absolute path
  • Values are not automatically type-converted; all values are returned as strings
  • The function does not support multi-line values or quoted strings with special characters
  • For production use, consider using the python-dotenv library which handles edge cases better

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_config_v1 83.1% similar

    Parses a .env file and loads key-value pairs into a dictionary, ignoring comments and handling errors gracefully.

    From: /tf/active/vicechatdev/SPFCsync/grant_sharepoint_access.py
  • function get_env_value 55.4% similar

    Retrieves an environment variable value by key and automatically strips surrounding single or double quotes if present.

    From: /tf/active/vicechatdev/email-forwarder/src/config/settings.py
  • function save_config_to_file 53.9% similar

    Persists current application configuration values from the config module to a .env file, maintaining existing entries and formatting multi-value fields appropriately.

    From: /tf/active/vicechatdev/docchat/app.py
  • function check_configuration_v1 52.0% similar

    Validates the presence of a .env configuration file and checks that all required environment variables (TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL) are defined.

    From: /tf/active/vicechatdev/email-forwarder/run_service.py
  • function load_config 47.7% similar

    Loads configuration settings from a file by instantiating and returning a Config object with the specified configuration file path.

    From: /tf/active/vicechatdev/contract_validity_analyzer/config/config.py
← Back to Browse