How to Create requirements.txt in Python Easily
To create a
requirements.txt file in Python, use the command pip freeze > requirements.txt in your project environment. This saves all installed packages and their versions into the file for easy sharing and installation.Syntax
The basic command to create a requirements.txt file is:
pip freeze > requirements.txt
Here, pip freeze lists all installed packages with their versions, and > redirects this list into the file named requirements.txt.
bash
pip freeze > requirements.txt
Example
This example shows how to create a requirements.txt file from your current Python environment and then display its contents.
python
import os # Create requirements.txt by running pip freeze os.system('pip freeze > requirements.txt') # Read and print the contents of requirements.txt with open('requirements.txt', 'r') as file: content = file.read() print(content)
Output
absl-py==1.4.0
attrs==23.1.0
certifi==2023.5.7
... (other packages listed) ...
Common Pitfalls
Common mistakes when creating requirements.txt include:
- Running
pip freezeoutside your project environment, which lists global packages instead of project-specific ones. - Manually editing the file and introducing syntax errors.
- Not updating the file after adding or removing packages.
Always activate your virtual environment before running pip freeze to capture only your project's dependencies.
bash
## Wrong way: Running pip freeze globally # pip freeze > requirements.txt ## Right way: Activate virtual environment first # source venv/bin/activate # On Linux/macOS # .\venv\Scripts\activate # On Windows # pip freeze > requirements.txt
Quick Reference
- Create requirements.txt:
pip freeze > requirements.txt - Install from requirements.txt:
pip install -r requirements.txt - Update requirements.txt: Run
pip freeze > requirements.txtafter changing packages
Key Takeaways
Use
pip freeze > requirements.txt inside your virtual environment to create the file.The file lists all installed packages with exact versions for easy sharing and installation.
Always activate your project’s virtual environment before creating the file to avoid global packages.
Update the file whenever you add or remove packages to keep it accurate.
Use
pip install -r requirements.txt to install dependencies from the file.