How to Create Requirements.txt File in Python (original) (raw)

Last Updated : 13 Mar, 2025

Creating and maintaining a **requirements.txt file is a fundamental best practice for Python development. It ensures that your project's dependencies are well-documented and easily reproducible, making it easier for others to work on your code and reducing the likelihood of compatibility issues.

Why Use a requirements.txt File?

A requirements.txt file serves several important purposes:

Steps to Create a requirements.txt File

Step 1: Set up a virtual environment

Using a virtual environment isolates your project’s dependencies, preventing conflicts with system-wide Python packages.

# Create a virtual environment
python -m venv myenv

# Activate the virtual environment

# on Windows
myenv\Scripts\activate

# on macOS and Linux
source myenv/bin/activate

Step 2: Install Dependencies

Install the necessary dependencies for your project using pip. Replace package-name with the actual package you want to install.

pip install package-name

For example, to install pandas:

pip install pandas

Step 3: Generate the requirements.txt File

Once all required packages are installed, generate the requirements.txt file by running:

pip freeze > requirements.txt

This command captures all installed dependencies and their versions in the file.

Step 4: Review your requirement.txt file

After generating the file, review its contents using :

cat requirements.txt

It should list installed packages with their versions, like:

pandas==1.5.3

numpy==1.23.5

Step 5: Install dependencies from requirement.txt

When setting up the project on a new system, install all dependencies using:

pip install -r requirements.txt

This ensures that all required packages are installed with the specified versions.

Screenshot-from-2023-09-09-13-01-39

Best Practices for Managing requirements.txt