How to add to the PYTHONPATH in Windows, so it finds my modules/packages?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Python's extensibility and modularity are among its greatest strengths, allowing users to create and import customized modules and packages. However, to leverage these, Python must know where to look for them. This is where PYTHONPATH
, an environment variable, plays a crucial role. In this article, you’ll learn how to set or modify PYTHONPATH
in a Windows environment to ensure Python can locate your modules and packages.
Understanding PYTHONPATH
PYTHONPATH
is an environment variable used by Python to specify the locations where the Python interpreter should look for modules and packages. It supplements the default search paths hardcoded into Python and can be particularly useful for development purposes or when working with virtual environments.
Step-by-Step Guide to Customize PYTHONPATH on Windows
Method 1: Temporary PYTHONPATH for a Session
- Open Command Prompt: Open the command prompt from the Start Menu or by pressing
Win + R, typingcmd, and pressingEnter. - Set the PYTHONPATH: You can temporarily set the
PYTHONPATHfor the current session using thesetcommand. For instance:- Right-click on 'This PC' or 'Computer' on the desktop and select 'Properties'.
- Click on 'Advanced system settings' from the left sidebar.
- Under the 'System Properties' window, switch to the 'Advanced' tab, and click 'Environment Variables'.
- In the 'Environment Variables' window, check if a
PYTHONPATHvariable already exists under 'User variables' or 'System variables'. - If it exists, select it and click 'Edit'. Otherwise, click 'New' to create a new environment variable.
- Variable name:
PYTHONPATH - Variable value:
C:\path\to\your\modules(use semicolons to separate multiple paths, e.g.,C:\path\one;C:\path\two)
- Using
.pthFiles: Alternatively, you can add paths by creating a.pthfile in one of the site-packages directories. Python reads these files to automatically include directories listed inside them. - Environment Variable Precedence: Be aware that
PYTHONPATHsettings are overridden by thesys.pathlist manipulated during script execution. The initial entries insys.pathtake precedence. - Check Existing sys.path: To see the current module search paths used by Python:

