LoginSignup
0
0

More than 1 year has passed since last update.

【Python】モジュール探索パスの追加方法

Posted at

モジュール探索パスを追加してインポートする方法をメモしておく。

モジュール探索パスの追加方法

モジュール探索パスとは、Pythonのimport文で自作のモジュールなどをインポートする際に探索されるパスのこと。これを追加することで絶対インポートができ、カレントディレクトリによらず上位ディレクトリでも正しくインポートできる。
モジュール検索パスは、標準ライブラリのsysモジュールであるsys.pathに格納されている。そこに、append()メソッドを使用して、パスを追加する。

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))

ここで、os.path.join()は引数で与えられたパスを結合する。
また、os.path.dirname(__file__)は実行ファイルのディレクトリ名を取得できる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0