How to Load a .env File Manually in Python

Parse a .env-style key-value file into a Python dictionary using only the standard library, with comment and quoted-value handling.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

37 lines
Python 3.9+
import re
from pathlib import Path


def load_dotenv_file(filepath: str) -> dict[str, str]:
    """Parse a .env-style file into a dictionary."""
    env = {}
    path = Path(filepath)

    if not path.exists():
        raise FileNotFoundError(f"Environment file not found: {filepath}")

    for line in path.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        key, _, value = line.partition("=")
        key = key.strip()
        value = value.strip()
        if not key:
            continue
        if len(value) >= 2 and value.startswith('"') and value.endswith('"'):
            value = value[1:-1]
        env[key] = value

    return env


if __name__ == "__main__":
    import tempfile

    with tempfile.NamedTemporaryFile(mode="w", suffix=".env", delete=False) as f:
        f.write("# Development settings\nDB_HOST=localhost\nDB_PORT=5432\n")
        env_path = f.name

    env_data = load_dotenv_file(env_path)
    print(env_data)

Output

stdout
{'DB_HOST': 'localhost', 'DB_PORT': '5432'}

How it works

The Path.read_text() method reads the file and .splitlines() iterates each line. partition("=") splits each line safely into key and value, even if the value contains an '=' character. Leading/trailing whitespace is stripped, and lines that are empty or start with '#' are ignored. The code optionally removes surrounding double quotes from values to handle quoted strings in .env files.

Common mistakes

  • Forgetting to strip whitespace from keys and values before storing them
  • Assuming every line has an '=' sign without using `partition()` or `split('=', 1)`
  • Not handling quoted values that contain commas or equals signs
  • Reading the file with a context manager but not using proper error handling for missing files

Variations

  1. Use `line.split('=', 1)` with a try/except instead of `partition()`
  2. Add support for single quotes as well as double quotes around values

Real-world use cases

  • Loading local environment variables in a development script without depending on a third-party library like python-dotenv.
  • Parsing a custom configuration file that follows the KEY=VALUE format in a small CLI tool or service.
  • Handling secret injection in a Docker entrypoint script where only the standard library is available.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.