A virtual environment in Python is an isolated workspace that has its own Python interpreter and installed packages. Each project can have its own environment, so package versions never clash across projects.
This is especially useful when:
requirements.txt file.myenv): contains its own Python and libraries.
# Create a virtual environment named "myenv"
python -m venv myenv
This creates a folder called myenv containing a fresh Python environment.
# On Windows (Command Prompt)
myenv\Scripts\activate
# On Windows (PowerShell)
myenv\Scripts\Activate.ps1
# On macOS/Linux
source myenv/bin/activate
After activation, your terminal prompt usually shows the environment name, for example: (myenv) C:\Users\YourName>.
# Deactivate the current virtual environment
deactivate
# Install packages inside the active virtual environment
pip install requests
# Save all installed packages to requirements.txt
pip freeze > requirements.txt
# Install packages from requirements.txt
pip install -r requirements.txt
Example workflow: create an environment for a project, install a package, and use it in a script.
# 1) Create and activate a virtual environment
python -m venv myenv
# Activate it (command depends on your OS)
# 2) Install a package inside the environment
pip install requests
# 3) Create a Python file (app.py) and use the package
# app.py
import requests
response = requests.get("https://api.github.com")
print("Status code:", response.status_code)
# 4) Run your script using the environment's Python
python app.py
venv command creates an isolated folder with its own Python and pip.pip install goes into that environment only.pip install requests downloads and installs the requests library inside myenv.python app.py uses the environment’s Python and finds requests there.pip freeze > requirements.txt to save all dependencies for sharing or deployment.pip install -r requirements.txt to quickly set up the same environment on another machine.project_env in a new folder.project_env and install numpy and pandas.pip freeze > requirements.txt and inspect the generated file.pip install -r requirements.txt to restore all packages.numpy and verify it works only when the environment is active.