I would like to import from the current working directory. For example:
import os
import pathlib
import tempfile
from importlib import import_module
with tempfile.TemporaryDirectory() as temp_dir:
tmp_dir = pathlib.Path(temp_dir)
(tmp_dir / "foo").mkdir()
(tmp_dir / "foo" / "__init__.py").write_text("def bar(): pass")
orig = os.getcwd()
os.chdir(tmp_dir)
print(import_module("foo"))
os.chdir(orig)
However:
Traceback (most recent call last):
File "/Users/tdegeus/data/prog/src/conda_envfile/t.py", line 12, in <module>
print(import_module("foo"))
^^^^^^^^^^^^^^^^^^^^
File "/Users/tdegeus/miniforge3/envs/pre/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'foo'
(It does work if the directory exists prior to execution.)
PYTHONPATHenvironment variable prepended to the list. Changing current working directory won't change add the new directory to the list, as Hai Vu noted in his answer. Just curious, what's the intended use of this? If you wrote the temp file to the current working directory, it should actually work, but I haven't tested it.