function load_env_file
Reads and parses environment variables from a .env file in the current directory, returning them as a dictionary.
/tf/active/vicechatdev/SPFCsync/validate_config.py
58 - 77
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
- This function does not automatically set environment variables in os.environ; you must manually set them using os.environ.update(env_vars) if needed
- The function uses split('=', 1) to handle values that contain '=' characters correctly
- Always check if the return value is None before attempting to access the dictionary
- The .env file should be in the current working directory where the script is executed
- Consider using python-dotenv library for production applications as it handles edge cases better
- The function strips whitespace from both keys and values, so 'KEY = VALUE' and 'KEY=VALUE' are treated identically
- Values are not quoted or unquoted automatically; if your .env file has quotes around values, they will be included in the returned string
- The function does not support multi-line values or variable interpolation
- Error messages are printed to stdout; consider logging or raising exceptions for better error handling in production code
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_config 83.1% similar
-
function main_v19 42.4% similar
-
function load_analysis_data 40.0% similar
-
function parse_log_line 33.4% similar
-
function test_configuration 33.2% similar