Python

Stdlib .env Loader (no dependency)

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Parse a `.env` file into a dict and optionally export to os.environ. Skips comments and blank lines, strips surrounding quotes — no python-dotenv dependency needed.
Python
Raw
import os
from pathlib import Path

def load_env(path: str | Path = ".env", export: bool = True) -> dict[str, str]:
    out: dict[str, str] = {}
    if not Path(path).exists():
        return out
    for raw in Path(path).read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, _, val = line.partition("=")
        key = key.strip()
        val = val.strip()
        if len(val) >= 2 and val[0] == val[-1] and val[0] in ('"', "'"):
            val = val[1:-1]                # strip wrapping quotes
        out[key] = val
        if export:
            os.environ.setdefault(key, val)
    return out

load_env()                         # loads .env and exports to os.environ
db_url = os.environ.get("DATABASE_URL")
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.