I have a module foo, containing util.py and bar.py.
I want to import it in IDLE or python session. How do I go about this?
I could find no documentation on how to import modules not in the current directory or the default python PATH.
After trying import "<full path>/foo/util.py"
,
and from "<full path>" import util
The closest I could get was
import imp
imp.load_source('foo.util','C:/.../dir/dir2/foo')
Which gave me Permission denied on windows 7.
This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.
append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.
To make sure Python can always find the module.py , you need to: Place module.py in the folder where the program will execute. Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can place the module.py in one of the folders included in the PYTHONPATH variable.
One way is to simply amend your path:
import sys
sys.path.append('C:/full/path')
from foo import util,bar
Note that this requires foo to be a python package, i.e. contain a __init__.py
file. If you don't want to modify sys.path
, you can also modify the PYTHONPATH
environment variable or install the module on your system. Beware that this means that other directories or .py
files in that directory may be loaded inadvertently.
Therefore, you may want to use imp.load_source
instead. It needs the filename, not a directory (to a file which the current user is allowed to read):
import imp
util = imp.load_source('util', 'C:/full/path/foo/util.py')
You could customize the module search path using the PYTHONPATH
environment variable, or manually modify the sys.path
directory list.
See Module Search Path documentation on python.org.
Give this a try
import sys
sys.path.append('c:/.../dir/dir2')
import foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With