function load_config_v1
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
- Always check if the returned value is None before accessing configuration keys
- Use .get() method on the returned dictionary to safely access keys with default values
- Ensure the .env file is in the current working directory or modify the function to accept a file path parameter
- Consider using the python-dotenv library for production applications as it handles more edge cases
- Do not commit .env files to version control; add .env to .gitignore
- All values are returned as strings; convert to appropriate types (int, bool, etc.) as needed
- The function does not handle quoted values or escape sequences; values are taken as-is after the first = sign
- Multi-line values are not supported by this implementation
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_env_file 83.1% similar
-
function save_config_to_file 63.8% similar
-
function load_config 58.5% similar
-
function check_configuration_v1 56.3% similar
-
function load_connection_config 55.6% similar