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

I use

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

to import some module.

How to add a permanent D:/my_library_folder/ folder to the Python library path so that I can only use

 import mymodule 

in future?

(Even after reboot, etc.)

+7
python path environment-variables anaconda
source share
3 answers

just put the folder in the site-packages directory. i.e:

 C:\PythonXY\Lib\site-packages 

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


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

If you have 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 into module.py like:

 from <my_library_folder> import module 

If you delete the __init__.py file, Python will no longer search for submodules inside this directory, so attempts to import the module will fail.

If you have many folders, create an empty __init__.py file in each folder. eg:

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

Set the PYTHONPATH environment variable to D: / my_library_folder /

+2
source share

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

+1
source share

All Articles