Open In App

How to Create Requirements.txt File in Python

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.

Create Requirements.txt File in Python

When working on Python projects, managing dependencies is a crucial part of the development process. Dependencies are external libraries or packages that your Python code relies on to function correctly. To ensure that your project is easily reproducible and maintainable, it’s a good practice to create a requirements.txt file. This file lists all the dependencies your project needs, making it easier for others to install and run your code.



Why Use a requirements.txt File?

A requirements.txt file serves several important purposes:

Creating a requirements.txt File

Step 1: Activate Your Virtual Environment



To create and activate a virtual environment, open your terminal and run the following commands:

# Create a virtual environment 
python -m venv myenv

# Activate the virtual environment

# Windows
myenv\Scripts\activate
# macOS and Linux
source myenv/bin/activate

Step 2: Install Dependencies

Before you can list your project’s dependencies in the requirements.txt file, you need to install them in your virtual environment. You can use pip, Python’s package manager, for this purpose. Here, Replace package-name with the actual name of the package you want to install.

pip install package-name
i.e. pip install pandas

Step 3: Generate the requirements.txt File

Now, you can generate the requirements.txt file by running the following command:

pip freeze > requirements.txt

Step 4: Review your requirement.txt file

Article Tags :