Parse .env Files

Load environment variables from a .env file.

Code

Python
# Manual parsing (no external deps)
def load_env(path=".env"):
    env = {}
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, val = line.split("=", 1)
                env[key.strip()] = val.strip().strip('"').strip("'")
    return env

env = load_env()
print(env.get("DATABASE_URL"))

Line-by-line explanation

Expected output

postgresql://localhost/mydb

Related snippets