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.1Anyone who gets your project can install everything with one command:
pip install -r requirements.txtThe -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.txtThe > 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.
- Create a variable named
requirements_textand assign it the string"numpy==1.26.4\npypdf==4.1.0\nrich==13.7.0". - Create a variable named
packagesand assign itrequirements_text.split("\n"). - Loop through
packageswith loop variablepackage. Inside the loop, callsplit("==")onpackageand assign the result to a variable namedparts. Callprint()withf"Package: {parts[0]}, Version: {parts[1]}". - Call
print()withf"Total packages: {len(packages)}".
# Step 1: Create the requirements_text string # Step 2: Split into a list of packages # Step 3: Loop through packages, split each on "==", print name and version # Step 4: Print the total number of packages
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding