function load_config
Parses a .env file and loads key-value pairs into a dictionary, ignoring comments and handling errors gracefully.
/tf/active/vicechatdev/SPFCsync/grant_sharepoint_access.py
10 - 22
simple
Purpose
This function provides a simple configuration loader that reads environment variables from a .env file in the current working directory. It parses each line for key=value pairs, skips comment lines (starting with #), and returns a dictionary containing all configuration values. Useful for managing application settings, API keys, and other configuration parameters without hardcoding them in source code.
Source Code
def load_config():
"""Load configuration from .env file."""
config = {}
try:
with open('.env', 'r') as f:
for line in f:
if '=' in line and not line.strip().startswith('#'):
key, value = line.strip().split('=', 1)
config[key] = value
return config
except Exception as e:
print(f"Error loading config: {e}")
return None
Return Value
Returns a dictionary (dict) where keys are configuration variable names (strings) and values are their corresponding values (strings) from the .env file. Returns None if an error occurs during file reading or parsing (e.g., file not found, permission denied).
Usage Example
# Create a .env file first:
# API_KEY=abc123
# DATABASE_URL=postgresql://localhost/mydb
# DEBUG=true
config = load_config()
if config:
api_key = config.get('API_KEY')
db_url = config.get('DATABASE_URL')
debug_mode = config.get('DEBUG') == 'true'
print(f"API Key: {api_key}")
print(f"Database: {db_url}")
else:
print("Failed to load configuration")
Best Practices
- Ensure the .env file exists before calling this function or handle the None return value appropriately
- This is a basic implementation; consider using the python-dotenv library for production use cases with better error handling and features
- The function reads from the current working directory; ensure your script is executed from the correct location or modify to use absolute paths
- All values are returned as strings; convert to appropriate types (int, bool, etc.) after retrieval
- Never commit .env files containing sensitive information to version control
- The function splits on the first '=' only, allowing values to contain '=' characters
- Empty lines and lines without '=' are silently skipped
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_env_file 83.1% similar
-
function test_configuration 47.4% similar
-
function main_v19 45.5% similar
-
function load_analysis_data 42.2% similar
-
function parse_log_line 35.8% similar