How to rename (or backup) a Python virtual environment?

I find it much easier to create a venv with the same packages than renaming one. I found magic sed commands and directory traversal scripts, but they did a half work or nothing. I found out that recreating an env is easier and faster.

Activate the old venv and query the packages with pip freeze:

pip freeze > requirements.txt

The command will write a requirements.txt file with the currently installed packages and versions.

Save this file for later use!

Create a new venv with the desired name:

python3 -m venv test_venv

Activate the new environment:

source test_venv/bin/activate

Now we can install the packages from our old environment with using the requirements.txt file:

pip install -r requirements.txt

Now the old env can be deleted or moved away.

If you have a comment or other opinion, visit Tom’s IT Cafe Discord Server and share it!

Leave a comment