requirements.txt
is a text file that lists the packages required for a Python project. It is used to specify the package dependencies for a project so that users can install all the required packages using a single command.
How to create requirements.txt?
To create a requirements.txt
file for a Python project, you can use the following steps:
- Make sure you have a virtual environment set up for your project. This will allow you to install the required packages in an isolated environment, which can be helpful when you have multiple projects with different package requirements. You can follow my article on creating a virtual environment blog mentioned below.
- Activate your virtual environment:
$ source env/bin/activate
- Install the required packages using
pip
, the package manager for Python. For example, to install therequests
andnumpy
packages, you can run:
$ pip install requests numpy
- Once you have installed the required packages, you can create a
requirements.txt
file by running:
$ pip freeze > requirements.txt
This will create a requirements.txt
file in the current directory, which will contain a list of all the packages and their respective versions that are installed in your virtual environment.
- You can then commit the
requirements.txt
file to version control and share it with others so that they can easily install the required packages for your project.
$ git add requirements.txt
$ git commit -m "Add requirements.txt"
Installing packages from requirements.txt
You can also use the requirements.txt
file to install the required packages in another environment. To do this, activate your virtual environment, then run the:
$ pip install -r requirements.txt
This will install all the packages listed in the requirements.txt
file.
You can also specify a specific version of a package in the requirements.txt
file. For example:
requests==2.24.0
numpy==1.19.2
This will install the specific versions of the requests
and numpy
packages that are specified in the file.
It’s a good idea to regularly update the requirements.txt
file to include the latest versions of the packages that your project depends on. You can do this by running pip freeze > requirements.txt
again after you have updated your packages.