Introduction
When you move a Python project to a different directory, modules that previously worked can suddenly raise ModuleNotFoundError. This happens because Python's sys.path is tied to the script location, virtual environment paths are absolute, and editable installs reference the original path.
This issue commonly affects developers who reorganize their workspace, move projects between machines, or use symlinked directories.
Symptoms
- python -m mypackage raises "ModuleNotFoundError: No module named mypackage"
- Previously working imports fail after moving the project folder
- Editable install still points to the old directory location
Common Causes
- Virtual environment stores absolute paths to the original project location
- PYTHONPATH environment variable referenced the old directory
- Editable install (pip install -e .) has a .pth file pointing to the old path
Step-by-Step Fix
- 1.Recreate the virtual environment in the new location: Delete old venv and create a fresh one.
- 2.```bash
- 3.# Remove old virtual environment
- 4.rm -rf venv # Linux/macOS
- 5.# rmdir /s /q venv # Windows
# Create new environment python -m venv venv source venv/bin/activate # Linux/macOS # venv\Scripts\activate # Windows
# Reinstall dependencies pip install -r requirements.txt ```
- 1.Reinstall editable packages: Update the .pth files to point to the new location.
- 2.```bash
- 3.# Reinstall in editable mode from the new location:
- 4.cd /new/project/path
- 5.pip install -e .
# Or reinstall all editable packages: pip install -e . --force-reinstall --no-deps ```
- 1.Check and fix PYTHONPATH: Remove stale paths from environment variable.
- 2.```bash
- 3.# Check current PYTHONPATH
- 4.echo $PYTHONPATH # Linux/macOS
- 5.echo %PYTHONPATH% # Windows
# Unset if pointing to old location: unset PYTHONPATH # Linux/macOS set PYTHONPATH= # Windows ```
- 1.Use relative imports within packages: Structure imports to be location-independent.
- 2.```python
- 3.# BAD: Absolute import breaks when path changes
- 4.import myproject.utils.helpers
# GOOD: Relative imports work regardless of project location # Inside myproject/main.py: from .utils import helpers from .models import User
# Run as a module (not a script) to make relative imports work: python -m myproject.main ```
Prevention
- Use pyproject.toml with build systems instead of manual path manipulation
- Keep virtual environments inside the project directory (venv/) so they move with the project
- Never hardcode absolute paths in configuration or import statements
- Use relative imports within packages and module execution (python -m)