How to Install Dependencies From a File in Python?

In Python, you can specify a list of dependencies by creating a "requirements.txt" file in the root directory of your Python project. Inside this file, each line should contain the package name and version, where the version can be:

  1. Specified by using various version specifiers, or;
  2. Omitted altogether to install the latest version.

For example:

# requirements.txt

flask==3.0.0 # pin to a specific version
numpy # install the latest version
pandas>=2.1.0 # specify minimum version requirement

Once you've created your "requirements.txt" file, you can install listed dependencies using a package manager such as pip (which is the default package manager for Python). To do so, open terminal and navigate to your project's directory, then run the following command:

pip install -r requirements.txt

This command will read the "requirements.txt" file and install all the specified dependencies.

Using a "requirements.txt" file is a common practice in Python development, especially when working on projects that need to be shared or deployed on different systems. It helps ensure that all developers and environments have the same set of dependencies installed.

You can also generate a "requirements.txt" file automatically based on the currently installed packages in your Python environment by using the pip freeze > requirements.txt command.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.