Python Virtual Environment – Keep Your Projects Clean & Organized

When working with Python, different projects often require different versions of packages.

A virtual environment helps you create an isolated space for each project — so changes in one project won’t affect others.



Why Use a Virtual Environment?



How to Create and Use a Virtual Environment

Step 1: Install virtualenv (if not already installed)

pip install virtualenv

Or for Python 3.3+, you can use built-in venv :

python -m venv env_name


Step 2: Create a Virtual Environment

virtualenv myenv

OR

python -m venv myenv

This creates a folder named myenv/ with an isolated Python setup.



Step 3: Activate the Environment

On Windows :

myenv\Scripts\activate


On macOS/Linux :

source myenv/bin/activate

Now your terminal will show (myenv) — meaning it's active.



Step 4: Install Packages

Now install any package only for this project :

pip install requests


Step 5: Deactivate the Environment

When you’re done :

deactivate


📁 Example Folder Structure

project-folder/
│
├── myenv/        ← virtual environment
├── main.py
├── requirements.txt


requirements.txt – Save All Your Packages

To share or deploy your project :

pip freeze > requirements.txt


Then install everything later with

pip install -r requirements.txt


Summary


Action Command
Create venv (Python 3) python -m venv myenv
Activate (Windows) myenv\Scripts\activate
Activate (Linux/mac) source myenv/bin/activate
Deactivate deactivate
Save packages list pip freeze > requirements.txt
Restore packages pip install -r requirements.txt


Real-Life Use Cases



Practice Python Code Here: