A virtual environment is an isolated folder that contains its own Python interpreter and separate set of installed packages for a specific project.
We create and manage using Python's built-in
venvmodule so that different projects do not break each other due to conflicting library versions.Why Use a Virtual Environment?
Prevent Version Conflicts. One project might need
requests 2.28, while another needsrequests 2.32. Separate environments let both projects run smoothly on the same computer.Protect Global Python. Installing packages inside a virtual environment keeps your main system Python clean and avoids administrator permission issues.
Simplify Sharing. You can export a list of the exact packages your project uses so teammates or deployment servers can recreate the setup easily.
# Create the Virtual Environment
python -m venv .venv
# Activate the Environment
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install Packages
pip install -r requirements.txt
# Save your current packages to a file
pip freeze > requirements.txt
# Install packages from an existing file
pip install -r requirements.txt
# Deactivate When Finished
deactivate