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.
Python code
29 linesimport 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
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
- Use `pip freeze` directly instead of `pip list --format=freeze` for the same result.
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.