Importing User Defined Modules In Python From A Directory
Solution 1:
When the file is printnumbers.py
, the module is called printnumbers
(without the .py
). Therefore use
import printnumbers
import sys
sys.path.append('/home/jake/Documents')
appends '/home/jake/Documents'
to the end of sys.path
. The directories listed in sys.path
are searched (in the order listed) whenever an import statement causes Python to search for a module. (Already imported modules are cached in sys.modules
, so Python does not always need to search sys.path
directories to import a module...)
So if you have a file /home/jake/Documents/printnumbers.py
, then import printnumbers
will cause Python to import it provided there is no other file named printnumbers.py
in a directory listed in sys.path
ahead of /home/jake/Documents/
.
Note that injecting directories into sys.path
is not the usual way to set up Python to search for modules. Usually it is preferable to add /home/jake/Documents
to your PYTHONPATH environment variable. sys.path
will automatically include the directories listed in the PYTHONPATH environment variable.
Solution 2:
and one more thing, use an empty __ init __.py file in you directory to make it as a python package (only then Python will know that this directory is a Python package directory other than an ordinary directory). Thus you can import modules from that package from different directory.
Post a Comment for "Importing User Defined Modules In Python From A Directory"