Python Modules, pip and Virtual Environments (venv) Explained for Beginners
P10.5 How to Use requirements.txt in Python Projects
Why. A teammate in another city must run your project with the same package versions. requirements.txt lists them.
What. A text file with one package per line, often with versions. pip freeze writes it; pip install -r reads it.
How.
Share your environment
- Activate the venv.
- Run
python -m pip freeze > requirements.txt. - Commit the file to Git (not the .venv folder).
- The teammate creates a venv and runs
python -m pip install -r requirements.txt.
Worked example A — Save and reinstall.
Step 1 — What we do. Freeze the packages, then install them on another laptop.
Step 2 — Type and run this code.
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt
Step 3 — What it means. The first line saves exact versions; the second recreates them anywhere.
Worked example B — Read a requirements file with Python.
Step 1 — What we do. We count packages listed in a requirements file.
Step 2 — Make the input file requirements.txt in the same folder as your code:
# data project
numpy==2.1.0
pandas==2.2.2
matplotlib==3.9.2
About this data: each non-comment line is one package and its exact version.
Step 3 — Type and run this code.
with open("requirements.txt", encoding="utf-8") as f:
pkgs = [l.strip() for l in f if l.strip() and not l.startswith("#")]
print(len(pkgs), "packages:", pkgs)
Step 4 — Output you should see.
3 packages: ['numpy==2.1.0', 'pandas==2.2.2', 'matplotlib==3.9.2']
Step 5 — What it means. It is just a text file — you already know how to read it.
Ravindra Bagale's Tip
Add .venv/ to your .gitignore. Share requirements.txt, never the venv folder itself.
Ravindra Bagale's Tip – मराठी
.venv/ तुमच्या .gitignore मध्ये टाका. requirements.txt share करा, venv folder कधीच नाही.
Ravindra Bagale's Tip – हिंदी
.venv/ अपनी .gitignore में डालो. requirements.txt share करो, venv folder कभी नहीं.