import from path in python

To import a module or package from a specific filepath in Python, you can use the sys.path attribute to temporarily add the filepath to the list of directories Python looks for modules in. Here's an example:

main.py
import sys
sys.path.append('/path/to/module_or_package')
import module_or_package
82 chars
4 lines

Replace /path/to/module_or_package with the actual path to the module or package containing the file(s) you want to import.

Alternatively, you can use the importlib module to dynamically load a module from a specific filepath. Here's an example:

main.py
import importlib.util
spec = importlib.util.spec_from_file_location('module_or_package', '/path/to/module_or_package/module_or_package.py')
module_or_package = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module_or_package)
241 chars
5 lines

Replace 'module_or_package' with the name of the module or package you want to import, and '/path/to/module_or_package/module_or_package.py' with the actual path to the file containing the module or package.

Note that importing from a specific filepath can be a security risk if you're not careful, as it can allow importing arbitrary code from untrusted sources.

gistlibby LogSnag