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.
Python code
37 linesimport 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
{'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
- Use `line.split('=', 1)` with a try/except instead of `partition()`
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.