Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

How to Audit Environment Variable Files for Missing Values in Python

A Python tool that reads an environment variable file and reports any variables with empty or missing values.

Medium Python 3.9+ Jun 28, 2026 Files & data 19 views 0 copies

Python code

38 lines
Python 3.9+
import os
import re
from pathlib import Path

def audit_env_file(filepath: str) -> None:
    """
    Audit an environment variable file for missing values.
    Prints file status and lists variables that have empty values.
    """
    path = Path(filepath)
    if not path.exists():
        print(f"Error: File '{filepath}' not found.")
        return

    missing = []
    with open(path, 'r') as f:
        for i, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            match = re.match(r'^([A-Za-z_]\w*)=(.*)$', line)
            if match:
                var_name = match.group(1)
                var_value = match.group(2).strip()
                if not var_value or var_value in ('""', "''"):
                    missing.append((i, var_name))
            else:
                print(f"Warning: malformed line {i}: '{line}'")

    print(f"Audit of '{filepath}' ({len(missing)} missing value(s)):")
    if missing:
        for line_num, var in missing:
            print(f"  Line {line_num}: '{var}' is empty")
    else:
        print("  All variables have assigned values.")

if __name__ == "__main__":
    audit_env_file(".env.example")

Output

stdout
Audit of '.env.example' (2 missing value(s)):
  Line 3: 'DB_PASSWORD' is empty
  Line 5: 'API_KEY' is empty

How it works

The function uses pathlib.Path to check file existence and then reads it line by line. A regex re.match extracts variable names and values, ignoring blank lines and comments. If a variable's value is empty or consists only of quotes ("" or ''), it's flagged as missing. The script prints a summary of all empty variables plus any malformed lines.

Common mistakes

  • Forgetting to strip lines before parsing, leading to false malformed-line warnings.
  • Assuming environment files always use `=` as delimiter without handling spaces around it.
  • Not considering that empty values can be intentional (e.g., `FEATURE_FLAG=` to disable).
  • Hardcoding a specific file name instead of accepting a filepath argument.

Variations

  1. Extend the tool to also validate required variables defined in a separate config file.
  2. Use `argparse` to accept multiple files or a directory of env files to audit.

Real-world use cases

  • Catching missing secrets before deploying a containerized application to production.
  • Validating that all contributors have filled in their local .env files after cloning a repo.
  • Integrating into a CI pipeline to fail a build if any required environment variable is unset.

Sponsored

Run this sample

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

Open editor

More from Files & data

Related tutorials and quizzes for this topic.