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
- 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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_config_v1 83.1% similar
-
function get_env_value 55.4% similar
-
function save_config_to_file 53.9% similar
-
function check_configuration_v1 52.0% similar
-
function load_config 47.7% similar