Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 987
Basj Avatar asked Dec 05 '13 08:12

Basj


People also ask

How do you add to a path in Python?

APPENDING PATH- append() is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search. The following example shows how this can be done.


1 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
like image 55
suhailvs Avatar answered Oct 12 '22 03:10

suhailvs