Pythonファイル内で別のPythonファイルをimportする際、 同じフォルダ内やサブフォルダ内にある場合は、以下でimportできます。
# myscript.pyをimportする import myscript # サブフォルダの場合 import folder.myscript
また、上記以外のフォルダのPythonファイルをimportする場合、一般的にはsys.path.append()を使ってファイルのディレクトリをpathに追加する方法を用います。
import sys sys.path.append(folder_path) import myscript
一方で、pathを追加したくない場面もあると思います。 その場合、importlib.utilを用いた以下の方法が可能です。
import importlib.util # Function to dynamically import a module given its full path def import_module_from_path(path): # Create a module spec from the given path spec = importlib.util.spec_from_file_location("module_name", path) # Load the module from the created spec module = importlib.util.module_from_spec(spec) # Execute the module to make its attributes accessible spec.loader.exec_module(module) # Return the imported module return module # Example usage module_path = '/path/to/your/module.py' module = import_module_from_path(module_path)