How to Generate an Inventory CSV of Installed pip Packages in Python

This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 14 views 0 copies

Python code

29 lines
Python 3.9+
import subprocess
import csv

def get_installed_packages():
    """Return a list of (name, version) tuples for installed pip packages."""
    result = subprocess.run(
        ["pip", "list", "--format=freeze"],
        capture_output=True,
        text=True,
        check=True
    )
    packages = []
    for line in result.stdout.strip().splitlines():
        if line and "==" in line:
            name, version = line.split("==", 1)
            packages.append((name, version))
    return packages

def write_inventory_csv(filename="packages_inventory.csv"):
    """Write installed packages to a CSV file with name and version columns."""
    packages = get_installed_packages()
    with open(filename, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["Package Name", "Version"])
        writer.writerows(packages)
    print(f"Wrote {len(packages)} packages to {filename}")

if __name__ == "__main__":
    write_inventory_csv()

Output

stdout
Wrote 42 packages to packages_inventory.csv

How it works

The subprocess.run call executes pip list --format=freeze and captures its output, which lists every installed package as name==version. The csv module writes these tuples into a CSV file with headers. Using check=True raises an error if pip fails, making the script fail loudly. This approach uses only the standard library, so no external dependencies are needed.

Common mistakes

  • Forgetting to set `newline=''` when opening the CSV file, which can cause unwanted line breaks on Windows.
  • Not filtering out empty lines or lines without `==`, which can cause parsing errors.
  • Using `pip list` without `--format=freeze` and trying to parse table output, which is fragile.

Variations

  1. Use `pip freeze` directly instead of `pip list --format=freeze` for the same result.
  2. Sort packages alphabetically before writing with `sorted(packages)`.

Real-world use cases

  • Generating a requirements manifest for reproducible deployment in CI/CD pipelines.
  • Automating dependency auditing by exporting installed versions for security scanning.
  • Creating a local backup of package versions before upgrading or migrating environments.

Sponsored

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.