How to use requirements.txt file in Python

Jul 11, 2024#python

A Python requirements file, usually named requirements.txt, is a plain text file that lists all the packages and dependencies needed for a Python project. This file makes it easy to install the required packages using a package manager like pip.

While pip is the primary tool associated with requirements.txt, other package managers like Pipenv, Poetry, Conda, pip-tools, and Hatch also support or integrate with requirements.txt in various ways. Each tool offers different features and benefits, so you can choose the one that best fits your project needs.

File creation and usage

You can manually create a requirements.txt file by listing the required packages. Alternatively, you can generate it using the pip command if you already have the packages installed in your environment:

pip freeze > requirements.txt

The requirements.txt file will not be automatically updated when you install a new package with pip. You need to manually update it or run pip freeze again to reflect the new dependencies.

It’s a good practice to include requirements.txt file in Git repository. Ensure that others (and future you) can recreate the same development environment with the exact same dependencies.

pip install -r requirements.txt

The filename requirements.txt is the conventional name used for a requirements file in Python projects, but it is not strictly required. You can use any filename you prefer. However, using requirements.txt is a widely recognized standard, making it easier for others to understand and work with your project.

If you choose to use a different filename, you will need to specify it explicitly when using pip commands. For example, if you name your file my_requirements.txt, you would install the dependencies with:

pip install -r my_requirements.txt

File structure

Each line of the requirements file indicates something to be installed, or arguments to pip install. The following forms are supported:

# requirements.txt
# This is a comment, to show how #-prefixed lines are ignored.
# It is possible to specify requirements as plain names.
pytest
pytest-cov
beautifulsoup4

# The syntax supported here is the same as that of requirement specifiers.
docopt == 0.6.1
requests [security] >= 2.8.1, == 2.8.* ; python_version < "2.7"
urllib3 @ https://github.com/urllib3/urllib3/archive/refs/tags/1.26.8.zip

# It is possible to refer to other requirement files or constraints files.
-r other-requirements.txt
-c constraints.txt

# It is possible to refer to specific local distribution paths.
./downloads/numpy-1.9.2-cp34-none-win32.whl

# It is possible to refer to URLs.
http://wxpython.org/Phoenix/snapshot-builds/wxPython_Phoenix-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl