Add a folder to the Python library path, once for all (Windows)

Viewed 45863

I use

sys.path.append('D:/my_library_folder/')
import mymodule

in order to import some module.

How to add permanently this folder D:/my_library_folder/ to the Python library path, so that I will be able to use only

import mymodule

in the future?

(Even after a reboot, etc.)

3 Answers

just put the folder in site-packages directory. ie:

C:\PythonXY\Lib\site-packages

Note: you need to add an empty file __init__.py to the folder


Files named __init__.py are used to mark directories on disk as a Python package directories.

If you have the files:

C:\PythonXY\Lib\site-packages\<my_library_folder>\__init__.py
C:\PythonXY\Lib\site-packages\<my_library_folder>\module.py

you can import the code in module.py as:

from <my_library_folder> import module

If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

If you have lots of folders, then create the empty __init__.py file in each folder. for eg:

C:\PythonXY\Lib\site-packages\<my_library_folder>\
    __init__.py
    module.py        
    subpackage\
        __init__.py
        submodule1.py
        submodule2.py

Set PYTHONPATH environment variable to D:/my_library_folder/

If D:/my_library_folder is a project you're working on and has a setup script, you could also do python setup.py develop. Not entirely related to the question, but I also recommend using virtualenv.

Related