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
- 1.Read file line by line.
- 2.Skip empty lines and comments (#).
- 3.Split on first = to get key and value.
- 4.Strip quotes from values.
Expected output
postgresql://localhost/mydb