📘 Lesson 27 · Advanced

Python Virtual Environments

Create and manage virtual environments with venv, pip, and requirements.txt.

Why Virtual Environments?

If you install all packages globally, two projects needing different versions of the same library will conflict. A virtual environment is an isolated Python installation per project — each project gets its own packages and versions, completely independent of others. Always use one for every Python project; it's the professional standard.

💡
Virtual environments prevent version conflicts and keep your system Python clean.

Create and Activate

Python's built-in venv module creates the environment. After activating, your terminal prompt shows the environment name and all pip installs go into that isolated folder.

terminal
# Create
python -m venv myenv

# Activate on Mac/Linux
source myenv/bin/activate

# Activate on Windows
myenv\Scripts\activate

# Prompt now shows:
(myenv) $
▶ Output
(myenv) $

Install Packages and Save Dependencies

terminal
# Install into the virtual environment
pip install requests flask pandas

# Save exact versions
pip freeze > requirements.txt

# Deactivate when done
deactivate
▶ Output
Successfully installed flask-3.0.0 pandas-2.1.4 requests-2.31.0

Recreating from requirements.txt

Never commit the venv/ folder — it's large and platform-specific. Commit requirements.txt instead. Anyone can recreate the exact environment with one command.

terminal
# After cloning a repo:
python -m venv myenv
source myenv/bin/activate
pip install -r requirements.txt
▶ Output
Successfully installed all packages.
⚠️
Add myenv/, venv/, and __pycache__/ to your .gitignore file. Never commit virtual environment folders.

🧠 Quick Check

Which file records all project dependencies for sharing?

packages.json
setup.py
requirements.txt
deps.txt

Tags

virtual environmentvenvpiprequirements.txtproject setup