Requirements Files
Exit

Requirements Files

Save and restore project dependencies with requirements.txt

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

The problem: reproducing an environment

You build a project on your machine and install 10 packages. A teammate clones the repo. How do they know which packages to install? They could read your code and guess, but that's slow and error-prone.

What requirements.txt does

A requirements file lists every package your project needs, one per line, with exact versions:

numpy==1.26.4
pypdf==4.1.0
google-genai==1.10.0
python-dotenv==1.0.1

Anyone who gets your project can install everything with one command:

pip install -r requirements.txt

The -r flag tells pip to read the file and install each listed package.

Creating a requirements file

The pip freeze command outputs every installed package in the exact format requirements.txt needs:

pip freeze > requirements.txt

The > operator redirects the output to a file instead of printing it to the terminal.

Why pinned versions matter

Notice the == syntax: numpy==1.26.4. This pins the version. Without pinning, pip install numpy installs the latest version — which might introduce breaking changes. Pinned versions guarantee that everyone who installs from your file gets the exact same packages you used.

Your task

Practice working with requirements data in Python. You will parse a requirements string, extract package names and versions, and build a summary. This mirrors what pip does internally when it reads requirements.txt.

Instructions

Parse a requirements string and extract package information.

  1. Create a variable named requirements_text and assign it the string "numpy==1.26.4\npypdf==4.1.0\nrich==13.7.0".
  2. Create a variable named packages and assign it requirements_text.split("\n").
  3. Loop through packages with loop variable package. Inside the loop, call split("==") on package and assign the result to a variable named parts. Call print() with f"Package: {parts[0]}, Version: {parts[1]}".
  4. Call print() with f"Total packages: {len(packages)}".