GoganWare

All about tech.

post banner

What is a requirements.txt file?

2 min read

A requirements.txt file is mostly used in virtual environments. Virtual environments provide a way to keep project dependencies isolated from other installed packages on a system and reduce errors when transferring the project to another location like another computer.

Many packages are updated regularly and oftentimes an issue can occur when a package is updated within a project. A project could break entirely during one of theses routine updates. You could also have the latest version of a package and when someone tries to run the application With an older version, they will likely come into some problems. With a requirements.txt file you have more control over versions of installed packages. Now, whenever anyone else uses the projects they will have the same dependencies as you.

Assuming you have PIP installed, run the following command to check what packages you have installed. Your virtual environment should be running before you enter this command.

pip freeze

You may need to run python -m if the above command does not work. If that doesn't work then you likely do not have pip installed.

python -m pip freeze

Here is what it might look like.

You can save this output to a requirements.txt like so

pip freeze > requirements.txt

You should now have a requirements.txt file in your current working directory with a list of installed packages. Now, when transferring your project you can simply send only your requirements.txt file instead of your entire virtual environment folder that has all the installed packages. If you were to download a repository from Github with a requirements.txt file you can easily install all the packages and their versions.

pip install -r requirements.txt

I hope this short guide helped your understanding of what a requirements.txt file is and when and how it can be useful.