趣味で計算流砂水理 Computational Sediment Hydraulics for Fun Learning

数値計算とか河川工学とかプログラミングのことを書いています

MENU

備忘録:Pythonファイルをフルパスでimportする方法(sys.path.append()を使わない方法)

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)

参考サイト:Dynamically Import a Module by Full Path in Python — Using importlib.util & sys | by Doug Creates | Medium