Reputation: 15
I have a string variable x, and want to use input to call a module in a subfolder, as shown below. How can I use this string as part of the path?
x = input()
from subfolder.x import y
My code is run from a parent folder 'main.py' and uses the line:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
to set the file path.
Upvotes: 0
Views: 634
Reputation: 36390
If you need to dynamically import, take look at importlib.import_module
consider following simple example
import importlib
modulename = "html"
submodulename = "entities"
what = "html5"
module = importlib.import_module(modulename + "." + submodulename)
thing = getattr(module,what)
print(thing["gt;"]) # >
Upvotes: 1
Reputation: 360
According to Python documentation, here is how an import
statement searches for the correct module or package to import:
When a module named
spam
is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file namedspam.py
in a list of directories given by the variablesys.path
.sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
After initialization, Python programs can modify
sys.path
. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.
Source: Python 2 and 3
So you can use sys.path.append
to append a location to the path, but once you close Python, sys.path
will be set back to default.
Or you can add the desired location permannently to PYTHONPATH
by adding
export PYTHONPATH="${PYTHONPATH}:/my/other/path"
in a startup script appropriate to whatever shell you're using (.bashrc
for bash, for example)
Upvotes: 0