Table of Contents

    requirements.txt

    CHAPTER 28.3 · PYTHON PACKAGE MANAGEMENT

    requirements.txt in Python

    Learn how to define, install, organize, verify, and maintain Python project dependencies using a requirements.txt file.

    Most Python projects depend on third-party packages. For example, a web application may need Flask, a data-analysis project may need Pandas, and an automation project may need Requests or OpenPyXL.

    Installing these packages manually on every computer is repetitive and can lead to inconsistent environments. A requirements.txt file provides a simple way to record the packages required by a Python project.

    Learning objective: In this tutorial, you will learn how to create a requirements file, install packages from it, use version specifiers, generate dependency lists, organize development dependencies, and avoid common mistakes.

    Prerequisites

    Before working with a requirements file, make sure the following requirements are available:

    What You Need

    • Python 3 should be installed on your computer.
    • pip should be available in the selected Python environment.
    • You should understand how to install a package using python -m pip install.
    • You should know how to create and activate a Python virtual environment.
    • A text editor or IDE should be available for creating and editing the requirements file.

    What is requirements.txt?

    A requirements.txt file is a text file containing package requirements that can be processed by pip.

    Each requirement is normally written on a separate line. A line may contain a package name, a package name with a version condition, a reference to another requirements file, a local package path, or another supported pip requirement.

    Think of requirements.txt as a project shopping list

    Instead of remembering and installing every package individually, the file provides pip with a list of the packages needed by the project.

    Why Use requirements.txt?

    Team Collaboration

    • Share project dependencies with other developers.
    • Reduce the need to communicate package names manually.
    • Help new team members configure the project environment.

    Environment Reproduction

    • Recreate a project environment on another computer.
    • Record package versions used during development.
    • Support automated build, test, and deployment workflows.

    Basic requirements.txt Format

    A basic requirements file may contain only package names:

    requests
    Flask
    pytest
    openpyxl

    In this example, pip selects package versions that satisfy the available requirements at installation time.

    A more controlled file may specify package versions:

    requests==2.32.3
    Flask>=3.0,<4.0
    pytest~=8.3
    openpyxl>=3.1

    Create a requirements.txt File

    Open the root directory of your Python project and create a new text file named:

    requirements.txt

    Add one package requirement per line:

    requests==2.32.3
    Flask>=3.0,<4.0
    python-dotenv>=1.0
    pytest>=8.0

    A simple project structure may look like this:

    my_project/
    |-- app.py
    |-- requirements.txt
    |-- README.md
    |-- src/
    |   `-- my_package/
    `-- tests/

    Install Packages from requirements.txt

    Activate the project's virtual environment and run:

    python -m pip install -r requirements.txt

    The -r option tells pip to read package requirements from the specified file.

    INSTALLATION FLOW
    requirements.txtpip install -rDependency ResolutionVirtual Environment

    Example installation output:

    Collecting requests==2.32.3
    Collecting Flask<4.0,>=3.0
    Collecting python-dotenv>=1.0
    Collecting pytest>=8.0
    Installing collected packages...
    Successfully installed required packages
    The exact package versions, dependencies, filenames, and displayed output depend on the requirements, Python version, operating system, configured package source, and installation environment.

    Version Specifiers

    Version specifiers tell pip which package versions are acceptable.

    Specifier Meaning Example
    == Require an exact version. requests==2.32.3
    >= Require the specified version or a newer version. Flask>=3.0
    <= Require the specified version or an older version. pytest<=8.3.5
    > Require a version greater than the specified version. openpyxl>3.0
    < Require a version lower than the specified version. Flask<4.0
    != Exclude a particular package version. requests!=2.31.0
    ~= Require a compatible release. pytest~=8.3

    Common Version Strategies

    1

    Unpinned Requirement

    The package name is provided without a version condition.

    requests
    Consideration Different installation dates may select different package versions.
    2

    Exact Version

    The requirement identifies one exact package version.

    requests==2.32.3
    Benefit Provides stronger control over the version requested during installation.
    3

    Version Range

    A minimum and maximum boundary define acceptable versions.

    Flask>=3.0,<4.0
    Benefit Allows compatible updates while excluding an unwanted major version.

    Add Comments

    A line beginning with the # character is treated as a comment and ignored by pip.

    # HTTP client used by the API integration
    requests==2.32.3
    
    # Web application framework
    Flask>=3.0,<4.0
    
    # Test framework
    pytest~=8.3

    Comments can make the purpose of direct dependencies easier to understand.

    Organize Requirements with Blank Lines

    Blank lines may be used to visually separate related dependency groups:

    # Application dependencies
    requests==2.32.3
    Flask>=3.0,<4.0
    python-dotenv>=1.0
    
    # Data processing
    pandas>=2.2
    openpyxl>=3.1
    
    # Testing
    pytest>=8.0
    pytest-cov>=5.0

    Install Package Extras

    Some packages define optional groups of additional dependencies, commonly called extras.

    Extras are written inside square brackets after the package name:

    package_name[extra_name]

    Example:

    uvicorn[standard]>=0.30

    Multiple extras may be separated by commas:

    package_name[extra_one,extra_two]>=1.0
    The available extras are defined by the package author. Review the package documentation before selecting an extra.

    Environment Markers

    Environment markers allow a requirement to be applied only when a specified environment condition is true.

    Operating-System Condition

    colorama>=0.4.6; sys_platform == "win32"

    Python-Version Condition

    importlib-metadata>=7.0; python_version < "3.10"

    Combined Example

    requests==2.32.3
    colorama>=0.4.6; sys_platform == "win32"
    importlib-metadata>=7.0; python_version < "3.10"

    Include Another Requirements File

    The -r option may be used inside a requirements file to include requirements from another file.

    requirements.txt:

    requests==2.32.3
    Flask>=3.0,<4.0
    
    -r requirements-dev.txt

    requirements-dev.txt:

    pytest>=8.0
    pytest-cov>=5.0
    black>=24.0
    If development packages should not be installed in production, do not automatically include the development file from the main production requirements file. Install it separately when needed.

    Use Separate Requirement Files

    Larger projects may use separate files for different environments or purposes.

    requirements/
    |-- base.txt
    |-- development.txt
    |-- testing.txt
    `-- production.txt

    requirements/base.txt:

    requests==2.32.3
    Flask>=3.0,<4.0
    python-dotenv>=1.0

    requirements/development.txt:

    -r base.txt
    
    black>=24.0
    ruff>=0.5

    requirements/testing.txt:

    -r base.txt
    
    pytest>=8.0
    pytest-cov>=5.0

    Install development dependencies:

    python -m pip install -r requirements/development.txt

    Requirements File vs Constraints File

    A requirements file identifies packages that should be installed. A constraints file limits acceptable package versions without independently requesting installation of every listed package.

    File Type Purpose
    Requirements File Defines packages or installable items that pip should process for installation.
    Constraints File Restricts versions considered during dependency resolution without acting as the primary package list.

    requirements.txt:

    Flask
    requests

    constraints.txt:

    Flask==3.0.3
    requests==2.32.3
    urllib3<3.0

    Install using both files:

    python -m pip install \
        -r requirements.txt \
        -c constraints.txt

    Generate requirements.txt with pip freeze

    After installing packages in a virtual environment, use pip freeze to generate requirements-format output:

    python -m pip freeze

    Redirect the output to requirements.txt:

    python -m pip freeze > requirements.txt

    Example generated output:

    blinker==1.8.2
    certifi==2025.4.26
    charset-normalizer==3.4.2
    click==8.1.7
    Flask==3.0.3
    idna==3.10
    requests==2.32.3
    urllib3==2.4.0
    pip freeze records installed packages in the current environment. It may include both direct dependencies and packages installed as supporting dependencies.

    Manually Maintained File vs pip freeze

    Manually Maintained

    • Can focus on direct project dependencies.
    • Can use version ranges instead of exact versions.
    • Comments can explain why each package is required.
    • Requires careful maintenance when dependencies change.

    Generated with pip freeze

    • Captures the current installed environment.
    • Usually includes direct and transitive dependencies.
    • Records exact installed versions.
    • Should be reviewed before sharing or committing.

    Upgrade Packages from requirements.txt

    To request upgrades that still satisfy the requirements file, use:

    python -m pip install \
        --upgrade \
        -r requirements.txt
    Test dependency upgrades in an isolated development or testing environment before applying them to an important application.

    Verify the Installed Environment

    After installing the requirements, list the installed packages:

    python -m pip list

    Check for missing or incompatible dependencies:

    python -m pip check

    Successful output:

    No broken requirements found.

    Test imports required by the application:

    import flask
    import requests
    import pytest
    
    print("Required packages imported successfully.")

    Recreate a Project Environment

    The following workflow creates a clean environment and installs the recorded project requirements.

    # Create a virtual environment
    python -m venv .venv
    
    # Activate it before continuing
    
    # Install the project requirements
    python -m pip install -r requirements.txt
    
    # Verify dependency compatibility
    python -m pip check
    
    # Review installed packages
    python -m pip list

    Common Problems and Solutions

    1

    File Not Found

    pip cannot locate the specified requirements file.

    Possible Error Could not open requirements file
    Solution Verify the filename and current terminal directory, or provide the correct relative or absolute file path.
    2

    Incorrect Package Name

    The package name in the file may be misspelled or unavailable from the configured package source.

    Possible Error No matching distribution found
    Solution Verify the exact distribution name and confirm that it supports the selected Python version and platform.
    3

    Conflicting Version Requirements

    Two or more dependencies may require incompatible versions of the same supporting package.

    Possible Error ResolutionImpossible
    Solution Review the conflicting requirements, package release notes, and supported version ranges. Adjust only after understanding the compatibility requirements.
    4

    Package Does Not Support the Python Version

    The selected package version may not support the Python interpreter used by the environment.

    Solution Review the package's supported Python versions and select a compatible package or Python version.
    5

    Unwanted Packages in requirements.txt

    A file generated with pip freeze may contain packages unrelated to the intended project.

    Solution Generate the file from a clean, project-specific virtual environment and review every entry before sharing it.

    Security and Dependency Review

    A requirements file causes third-party code to be installed into a Python environment. Every listed dependency should therefore be reviewed as part of the software supply chain.

    Safer Dependency Practices

    • Verify package names carefully before adding them.
    • Review package ownership, documentation, release history, source repository, and license where appropriate.
    • Be cautious of package names that resemble or misspell popular packages.
    • Review every change made to the requirements file.
    • Test package upgrades before applying them to important environments.
    • Do not store passwords, tokens, or private credentials inside a requirements file.
    • Use approved public or private package sources.
    • Follow organizational security, licensing, privacy, and open-source policies.

    Risky and Recommended Practices

    Risky Practices

    • Using only unpinned package names everywhere.
    • Generating the file from a global Python environment.
    • Adding packages without confirming why they are needed.
    • Mixing development and production packages without a clear structure.
    • Ignoring dependency-resolution errors.
    • Committing credentials or private tokens into the file.

    Recommended Practices

    • Maintain requirements inside a project-specific virtual environment.
    • Use suitable exact versions or controlled version ranges.
    • Separate application, development, testing, and production requirements when necessary.
    • Add comments for dependencies whose purpose is not obvious.
    • Run pip check after dependency changes.
    • Review and test all dependency updates.

    Complete Practical Example

    Create the following requirements.txt file:

    # Web application
    Flask>=3.0,<4.0
    
    # HTTP requests
    requests==2.32.3
    
    # Environment-variable support
    python-dotenv>=1.0,<2.0
    
    # Testing
    pytest>=8.0,<9.0

    Create and activate a virtual environment:

    python -m venv .venv

    Install the dependencies:

    python -m pip install -r requirements.txt

    Verify the installed environment:

    python -m pip list
    python -m pip check

    Create a file named verify_packages.py:

    import flask
    import requests
    import dotenv
    import pytest
    
    print("Flask version:", flask.__version__)
    print("Requests version:", requests.__version__)
    print("All required packages are available.")

    Run the verification program:

    python verify_packages.py

    Hands-On Practice

    Practice Assignment

    • Create a project folder named requirements-practice.
    • Create and activate a virtual environment.
    • Create a manually maintained requirements file.
    • Add Requests, Flask, pytest, and OpenPyXL.
    • Use at least two different version-specifier strategies.
    • Add comments explaining the purpose of each package.
    • Install the packages from the file.
    • Verify the environment using pip list and pip check.
    • Generate a second file using pip freeze.
    • Compare the manually maintained file with the generated file.

    Knowledge Check

    1

    What is requirements.txt?

    It is a text file containing package requirements that pip can process during installation.

    2

    How do you install packages from requirements.txt?

    python -m pip install -r requirements.txt
    3

    How do you generate requirements-format output?

    python -m pip freeze > requirements.txt
    4

    What does == mean?

    It requests an exact package version.

    5

    How do you include another requirements file?

    -r another-requirements.txt
    6

    How do you reference a constraints file?

    -c constraints.txt

    requirements.txt Quick Reference

    # Package without a version condition
    requests
    
    # Exact version
    requests==2.32.3
    
    # Minimum version
    Flask>=3.0
    
    # Version range
    Flask>=3.0,<4.0
    
    # Exclude a version
    requests!=2.31.0
    
    # Compatible release
    pytest~=8.3
    
    # Package extra
    uvicorn[standard]>=0.30
    
    # Environment marker
    colorama>=0.4.6; sys_platform == "win32"
    
    # Include another requirements file
    -r requirements-dev.txt
    
    # Apply a constraints file
    -c constraints.txt

    Common commands:

    # Install the requirements
    python -m pip install -r requirements.txt
    
    # Upgrade packages within the declared requirements
    python -m pip install --upgrade -r requirements.txt
    
    # Generate requirements-format output
    python -m pip freeze > requirements.txt
    
    # List installed packages
    python -m pip list
    
    # Display information about a package
    python -m pip show requests
    
    # Check dependency compatibility
    python -m pip check

    Summary

    What You Learned

    • A requirements file contains package requirements for pip.
    • Packages can be installed using python -m pip install -r requirements.txt.
    • Version specifiers control acceptable package versions.
    • Comments and blank lines can improve file readability.
    • Environment markers can apply packages conditionally.
    • Additional requirements and constraints files can be referenced from a requirements file.
    • pip freeze can capture packages installed in the current environment.
    • A requirements file should be reviewed, tested, and maintained whenever project dependencies change.

    Key Takeaway

    A well-maintained requirements.txt file makes Python dependencies easier to install, share, review, and reproduce. Use appropriate version constraints, keep the file focused on the project, and verify dependency compatibility after every significant change.