How to Create and Use a Virtual Environment in Python with venv
A Step-By-Step Guide to Using Virtual Environments in Python
Published by Carlo van Wyk on June 16, 2025 in Python

Why use a Virtual Environment?
You've likely encountered the frustration of package conflicts. Imagine working on Project A that requires Django 3.2, while Project B needs Django 4.1. Without proper isolation, installing one version overwrites the other, potentially breaking your applications. This is where Python virtual environments become essential.
The Problem with Global Package Installation
When you install Python packages globally using pip, they all share the same space in your system's Python installation.
This creates several problems:
- Dependency Conflicts
Different projects often require different versions of the same package. Installing a newer version for one project can break another project that depends on an older version. - System Pollution
Over time, your global Python environment becomes cluttered with packages from various projects, making it difficult to track what's actually needed for each project. - Deployment Issues
When you're ready to deploy your application, it's nearly impossible to determine exactly which packages and versions your project requires, leading to "it works on my machine" scenarios.
Benefits of Virtual Environments
Virtual environments solve these problems by creating isolated Python installations for each project.
Here are the key benefits:
- Project Isolation
Each project gets its own set of dependencies, separate from other projects and the system Python installation. - Version Control
You can use different versions of the same package across different projects without conflicts. - Clean Development
Your global Python installation stays clean, with only essential system packages installed. - Reproducible Environments
Virtual environments make it easy to recreate the exact same development environment on different machines or for different team members.
Here's how to use Python's built-in venv module to create and manage virtual environments.
Creating a Virtual Environment
To create a virtual environment, navigate to your project directory and run:
python -m venv myenv
Activating the Environment
Activate the virtual environment based on your operating system:
Windows:
myenv\Scripts\activate
Linux/macOS:
source myenv/bin/activate
Working with Packages
Install packages using pip while your virtual environment is activated:
pip install package_name
List all installed packages:
pip list
Managing Dependencies with requirements.txt
Generate a requirements.txt file with all installed packages:
pip freeze > requirements.txt
Install packages from requirements.txt:
pip install -r requirements.txt
Deactivating and Removing
Deactivate the virtual environment:
deactivate
To remove a virtual environment, simply delete the environment directory:
rm -rf myenv # Linux/macOS
rmdir myenv /s /q # Windows