A requirements.txt file helps manage and share project dependencies.
Generate requirements.txt
To create a requirements.txt file, you can use the pip freeze command, which outputs a list of installed packages and their versions.
For example:
pip freeze > requirements.txtInstall Packages from requirements.txt
To install the packages listed in the requirements.txt file, you can use the pip install command with the -r flag:
pip install -r requirements.txtThis ensures all necessary dependencies are installed when setting up the project on a new system.
Specifying Versions
You can manually edit requirements.txt to control versions:
Exact version:
Django==4.2.5At least this version:
requests>=2.25.0Any compatible version (up to next major release):
numpy~=1.24.0Why Use requirements.txt?
- Ensures all developers use the same package versions
- Makes deployment to servers or cloud services easier
- Saves time when setting up new environments
Best Practices
- Use a virtual environment (venv or conda) to avoid polluting your global Python setup
- Regenerate
requirements.txtwhenever dependencies change - Use
pip install --upgrade -r requirements.txtto update installed packages - Keep the file in your project root so it’s easy to find
👉 Next tutorial: Python Lambda Functions