Software Engineering

Python requirements.txt - Syntax, Examples & Best Practices

Python requirements.txt complete guide: pip freeze syntax, version pinning (==, >=, ~=), and pip install -r examples. Create reproducible Python environments.

By Inventive HQ Team

Master Python dependency management and eliminate "it works on my machine" problems forever. Learn to create, maintain, and optimize requirements.txt files for consistent Python environments across teams and deployments. If you've ever tried to share your Python project with a colleague or deploy it on a new machine, you may have run into the dreaded "It works on my machine" problem. This frustrating situation occurs when your code works perfectly in your environment but throws errors elsewhere due to missing or mismatched dependencies. Thankfully, Python provides a simple yet powerful solution: the requirements.txt file. By using this file, you can list all the dependencies your project needs, including their specific versions. This ensures that anyone working with your project can replicate your environment exactly, whether they're on a different computer, operating system, or deploying to a production server.

Try our free requirements.txt Generator to build and validate a requirements.txt file instantly in your browser.

What Is a requirements.txt File?

At its core, a requirements.txt file specifies the Python packages required to run your project. It's a simple text file that lists the dependencies your project needs, often with specific version numbers to ensure compatibility.

Why Is It Important?

The requirements.txt file serves as a blueprint for recreating your project's environment. Here's why it's essential:

  • Consistency Across Environments: Ensures everyone working on your project has the same setup, regardless of their system or operating system
  • Prevents Bugs: By locking in specific versions of packages, you avoid issues caused by breaking changes or updates in dependencies
  • Simplifies Collaboration: Instead of manually sharing which libraries are needed, you can share the requirements.txt file for quick project setup

Basic Format

A typical requirements.txt file contains one line for each package, followed by its version number. Here's an example:

pyOpenSSL==0.13.1
pyparsing==2.0.1
python-dateutil==1.5
pytz==2013.7
scipy==0.13.0b1
six==1.4.1
virtualenv==16.3.0

Each line specifies a package name and its version using ==. This ensures that the exact version you've tested your project with will be installed, helping to maintain stability and reliability.

Version Specifier Comparison Table

Python supports several version specifiers beyond the basic == operator. Here's a complete comparison:

SpecifierNameExampleMeaning
==Exact matchflask==2.0.1Only version 2.0.1
>=Minimum versionflask>=2.0.0Version 2.0.0 or higher
<=Maximum versionflask<=3.0.0Version 3.0.0 or lower
!=Exclusionflask!=2.0.0Any version except 2.0.0
~=Compatible releaseflask~=2.0.1>=2.0.1 and <2.1.0 (patch updates only)
^Caret (Poetry)flask^2.0.1>=2.0.1 and <3.0.0 (minor updates allowed)
>Greater thanflask>2.0.0Any version above 2.0.0
<Less thanflask<3.0.0Any version below 3.0.0
*Wildcardflask==2.0.*Any 2.0.x version

You can also combine specifiers for precise control:

# Allow versions 2.0.0 through 2.9.x, but not 3.0+
flask>=2.0.0,<3.0.0

# Require at least 1.0, exclude known buggy version
requests>=1.0,!=1.2.3

# Pin major version but allow patches
django>=4.2,<4.3

💡 Best Practice: For production applications, use == to pin exact versions. For libraries you publish, use >= with upper bounds to allow flexibility while avoiding breaking changes.

Why You Need a requirements.txt File

Using a requirements.txt file is not just a best practice in Python development—it's a game changer when it comes to managing dependencies and ensuring your projects run smoothly. Here are the key benefits:

1. Consistency

A requirements.txt file ensures that all team members and environments use the same versions of dependencies. Whether someone is working on a Mac, Windows, or Linux system, they can replicate your development environment with a single command. This eliminates the guesswork and avoids the dreaded "It works on my machine" scenario.

2. Ease of Collaboration

When sharing your project with others, the requirements.txt file makes it incredibly simple for them to set it up. Instead of manually installing dependencies, they can use the file to quickly install everything your project needs. This is especially useful for onboarding new team members or sharing your work in open-source projects.

3. Version Control

Dependencies often evolve, and package updates can sometimes introduce breaking changes. By specifying exact versions in the requirements.txt file, you lock your project to a stable, tested setup. This reduces the risk of bugs caused by updates and ensures your project remains functional over time.

4. Automation

The requirements.txt file is a critical component in deployment pipelines and continuous integration/continuous delivery (CI/CD) workflows. It automates dependency installation, allowing for seamless deployment of your project to production environments or testing frameworks without manual intervention.

How to Create a requirements.txt File

Creating a requirements.txt file is simple and can be done in two main ways: manually or automatically using the pip freeze command. Both approaches ensure you can document and manage the dependencies for your project effectively.

Manual Creation

If you already know the packages and versions your project requires, you can create a requirements.txt file manually. Here's how:

  • Open a text editor of your choice (e.g., Notepad, VS Code, or PyCharm)
  • List each package and its version on a new line in the following format:
package_name==version_number
  • Save the file as requirements.txt in the root directory of your project For example, your requirements.txt file might look like this:
tensorflow==2.3.1
flask==2.0.1
numpy==1.21.0

Using pip freeze

For a more automated approach, you can generate a requirements.txt file using the pip freeze command (or use our requirements.txt Generator for a guided, browser-based option). This method lists all installed packages in your current Python environment, along with their version numbers. Here's how to do it:

  • Open a terminal or command prompt
  • Navigate to your project directory
  • Run the following command:
pip freeze > requirements.txt

This command creates a requirements.txt file containing a list of all installed packages. 💡 Pro Tip: While pip freeze is convenient, it often includes packages that your project doesn't actually use, especially if your environment has been used for multiple projects. Consider using virtual environments for cleaner dependency management.

Install Packages from a requirements.txt File

Once you have a requirements.txt file, installing all the dependencies listed in it is straightforward. This process saves you time and ensures your project's environment is consistent across different systems.

Step-by-Step Guide

  • Open a Terminal or Command Prompt: Navigate to the directory where your requirements.txt file is located
  • Run the Installation Command: Use the following command to install all the dependencies listed in the file:
pip install -r requirements.txt
  • This command reads the file line by line and installs the specified packages and versions
  • Wait for the Installation to Complete: Once finished, you'll see output indicating that each package has been successfully installed

Troubleshooting Common Issues

While installing packages from a requirements.txt file is usually seamless, you might encounter issues. Here are some common problems and how to resolve them: ⚠️ Common Issue: Permission errors during installation can be resolved by using the --user flag: pip install -r requirements.txt --user

Using Virtual Environments

Virtual environments are a powerful tool in Python development. They allow you to isolate your project's dependencies from your system's global environment, ensuring that your project runs consistently and avoids conflicts with other projects.

What Is a Virtual Environment?

A Python virtual environment is a self-contained directory that contains a copy of the Python interpreter and its own independent set of installed packages. When you activate a virtual environment, any Python packages you install or modify are confined to that environment and won't interfere with other projects.

Advertisement

How to Use a Virtual Environment

Here's a step-by-step guide to creating and using a virtual environment:

  1. Create a Virtual Environment:
# Windows/Linux
python -m venv .venv

# macOS (using python3)
python3 -m venv .venv
  1. Activate the Virtual Environment:
# Windows
.venv\\Scripts\\activate

# macOS/Linux
source .venv/bin/activate
  1. Install Dependencies and Generate requirements.txt:
# Install packages
pip install flask numpy requests

# Generate requirements.txt
pip freeze > requirements.txt

# Deactivate when done
deactivate

💡 Best Practice: Always use virtual environments to keep your project dependencies isolated. This ensures your requirements.txt file contains only the packages your project actually needs, making it cleaner and more maintainable.

Best Practices for Using requirements.txt

To maximize the effectiveness of your requirements.txt file and maintain a smooth development process, follow these essential best practices:

  • Use Virtual Environments: Always generate your requirements.txt file from a virtual environment to ensure only necessary packages are included
  • Pin Package Versions: Specify exact versions using == operator to prevent unexpected behavior from updates
  • Keep in Version Control: Add requirements.txt to your Git repository for team collaboration
  • Regular Updates: Periodically update dependencies for security patches and bug fixes
  • Test After Updates: Always test your project after updating dependencies

Advanced Tools for Dependency Management

Consider these advanced tools for more sophisticated dependency management:

  • pip-tools: Automatically resolves dependency conflicts and generates requirements.txt from requirements.in files
  • Poetry: Modern Python dependency manager with automatic virtual environment handling
  • pipreqs: Generates requirements.txt by scanning your project's imports

Migrating to pyproject.toml

Python's packaging ecosystem is evolving toward pyproject.toml as the standard configuration file (PEP 621). While requirements.txt remains widely used, understanding when and how to migrate can future-proof your projects.

For a complete guide to pyproject.toml, see our pyproject.toml Complete Guide. For help deciding which file to use, see pyproject.toml vs requirements.txt vs setup.py.

When to Use Each Approach

Use CaseRecommendedReason
Simple scriptsrequirements.txtMinimal setup, widely understood
Applications (web apps, APIs)requirements.txtDeployment tools expect it
Reusable libraries/packagespyproject.tomlModern standard for distribution
Projects using Poetry/PDMpyproject.tomlNative format for these tools
Legacy projectsrequirements.txtDon't fix what isn't broken

Converting requirements.txt to pyproject.toml

If you're building a distributable package, here's how to migrate:

Original requirements.txt:

flask>=2.0.0
requests==2.28.1
python-dotenv~=1.0.0

Equivalent pyproject.toml:

[project]
name = "my-project"
version = "1.0.0"
description = "My Python project"
requires-python = ">=3.8"
dependencies = [
    "flask>=2.0.0",
    "requests==2.28.1",
    "python-dotenv~=1.0.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "black>=23.0",
]

Generating requirements.txt from pyproject.toml

Many deployment platforms still require requirements.txt. You can generate one from pyproject.toml:

# Using pip-tools (recommended)
pip install pip-tools
pip-compile pyproject.toml -o requirements.txt

# Using Poetry
poetry export -f requirements.txt --output requirements.txt

# Using PDM
pdm export -o requirements.txt

💡 Key Insight: You don't have to choose one over the other. Many projects use pyproject.toml as the source of truth and generate requirements.txt for deployment compatibility.

Security Considerations

When managing Python dependencies, security should be a top priority. Outdated packages can introduce vulnerabilities that put your application and data at risk. Here's how to maintain secure dependency management:

Automated Security Scanning

GitHub automatically scans requirements.txt files for known vulnerabilities and sends alerts when security issues are detected. This automated monitoring helps you stay ahead of potential threats without manual oversight.

Regular Dependency Audits

Use tools like pip-audit or safety to regularly scan your dependencies for known security vulnerabilities. These tools can be integrated into your CI/CD pipeline for continuous security monitoring. 🔒 Security Alert: Never ignore dependency security warnings. Outdated packages with known vulnerabilities can be entry points for cyberattacks. Regular updates and security audits are essential for maintaining a secure Python environment. Just as InventiveHQ provides comprehensive cybersecurity solutions for businesses, implementing secure dependency management practices protects your Python applications from potential threats and vulnerabilities.

Troubleshooting Common Errors

Here are solutions to the most frequent issues when working with requirements.txt files:

ERROR: Could not find a version that satisfies the requirement

ERROR: Could not find a version that satisfies the requirement package-name==1.0.0
ERROR: No matching distribution found for package-name==1.0.0

Causes and solutions:

  • Package doesn't exist: Check for typos in the package name (pip search is deprecated, use PyPI.org to verify)
  • Version doesn't exist: Run pip index versions package-name to see available versions
  • Python version incompatible: Some packages require specific Python versions. Check with python --version
  • Platform incompatible: Some packages are Windows/Linux/macOS only

ERROR: pip's dependency resolver does not currently take into account all the packages

ERROR: pip's dependency resolver does not currently take into account all packages

Solution: This warning appears when packages have conflicting dependencies. Use pip-tools for better resolution:

pip install pip-tools
pip-compile requirements.in --resolver=backtracking

Permission denied errors

ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied

Solutions:

# Option 1: Install for current user only (recommended)
pip install -r requirements.txt --user

# Option 2: Use a virtual environment (best practice)
python -m venv .venv
source .venv/bin/activate  # or .venv\Scripts\activate on Windows
pip install -r requirements.txt

Hash verification failed

ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE

Cause: Package files have changed since hashes were generated (security concern or mirror issue).

Solutions:

# Regenerate hashes (if you trust the current packages)
pip-compile --generate-hashes requirements.in

# Or remove hashes temporarily to debug
pip install -r requirements.txt --no-deps

Conflict between package versions

ERROR: Cannot install package-a and package-b because these package versions have conflicting dependencies.

Solution: Create a constraints file to force compatible versions:

# constraints.txt
problematic-package==1.2.3

# Install with constraints
pip install -r requirements.txt -c constraints.txt

SSL Certificate errors

ERROR: Could not fetch URL https://pypi.org/simple/: There was a problem confirming the ssl certificate

Solutions:

# Update certificates
pip install --upgrade certifi

# Temporary workaround (not recommended for production)
pip install -r requirements.txt --trusted-host pypi.org --trusted-host files.pythonhosted.org

Summary

The requirements.txt file is a simple yet powerful tool for managing Python dependencies. By listing the packages your project needs and their specific versions, you can ensure consistency, simplify collaboration, and streamline deployment. It's an essential practice for any Python developer, whether you're working solo or in a team. Key takeaways from this guide:

  • Requirements.txt files ensure consistent environments across different systems and team members
  • Virtual environments are essential for creating clean, isolated dependency lists
  • Regular updates and security audits protect your applications from vulnerabilities
  • Advanced tools like pip-tools and Poetry can enhance your dependency management workflow
  • Proper version pinning prevents unexpected issues from package updates Now that you've learned how to create, use, and maintain a requirements.txt file, it's time to put this knowledge into action. Start by setting up a virtual environment for your next project and using pip freeze to generate your own requirements.txt file.

Elevate Your IT Efficiency with Expert Solutions

Transform Your Technology, Propel Your Business

Unlock advanced technology solutions tailored to your business needs. At InventiveHQ, we combine industry expertise with innovative practices to enhance your cybersecurity, streamline your IT operations, and leverage cloud technologies for optimal efficiency and growth. Discover Our Services

Frequently Asked Questions

What is a requirements.txt file in Python?

A requirements.txt file is a text file that lists all Python packages (dependencies) your project needs to run. Each line contains a package name and optionally a version number (e.g., flask==2.0.1). It's the standard way to share project dependencies so others can install them with pip install -r requirements.txt.

How do I create a requirements.txt file?

Two methods: 1) Automatic: Run pip freeze > requirements.txt to export all installed packages in your environment. 2) Manual: Create a text file and list packages line by line (e.g., numpy==1.21.0). Best practice is to use a virtual environment first so you only capture your project's actual dependencies.

What is the difference between pip freeze and pip list?

pip list displays installed packages in a human-readable format. pip freeze outputs packages in requirements.txt format (package==version), ready for redirection to a file. Use pip freeze > requirements.txt to generate your requirements file, and pip list when you just want to see what's installed.

How do I install packages from requirements.txt?

Run pip install -r requirements.txt in your terminal. This reads each line of the file and installs the specified packages with their exact versions. Add the --user flag if you get permission errors: pip install -r requirements.txt --user.

What does == mean in requirements.txt?

The == operator pins an exact version (e.g., django==4.2.0 installs only version 4.2.0). Other operators: >= (minimum version), <= (maximum), ~= (compatible release), != (exclude version). Pinning exact versions with == is recommended for production to ensure reproducible builds.

Should I include requirements.txt in git?

Yes, always commit requirements.txt to version control. It's essential for team collaboration and deployment—anyone cloning your repo can recreate your exact Python environment. Also consider committing requirements-dev.txt for development dependencies (testing, linting tools) that aren't needed in production.

How do I update packages in requirements.txt?

To update all packages: 1) Run pip install --upgrade package_name for each package, or use pip-review --auto (from pip-review package). 2) Regenerate requirements.txt with pip freeze > requirements.txt. For safer updates, use pip-compile from pip-tools which resolves dependencies automatically.

What is the difference between requirements.txt and setup.py?

requirements.txt lists exact versions for reproducing an environment (deployment/development). setup.py (or pyproject.toml) defines package metadata and flexible dependency ranges for distributing your code as a library. Use requirements.txt for applications, setup.py/pyproject.toml for reusable packages.

How do I generate requirements.txt automatically?

Use pip freeze > requirements.txt to export all installed packages. For a cleaner file with only your project's direct dependencies (not sub-dependencies), use pipreqs: pip install pipreqs && pipreqs . which scans your imports. Always run these commands inside an activated virtual environment.

What does -r mean in pip install?

The -r flag tells pip to read package names from a requirements file. pip install -r requirements.txt reads each line of the file and installs those packages. You can also use -r to include other requirements files: add -r base.txt inside requirements.txt to inherit dependencies.

python requirements.txtpythonpipdependenciesrequirements filepip freeze
Advertisement