0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで親ディレクトリのモジュールをimportする

Posted at

ディレクトリ構成

parentdir
+-upper.py
+-subdir
  +-lower.py
upper.py
def upper_method():
    print("Upper method")
lower.py
import sys
import os
 
# このlower.pyがあるディレクトリ(subdir)
current = os.path.dirname(os.path.realpath(__file__))
print(f'{current=}')
 
# このlower.pyがあるディレクトリの親ディレクトリ(parentdir)
parent = os.path.dirname(current)
print(f'{parent=}')
 
# その親ディレクトリをsys.pathに追加
sys.path.append(parent)
 
# これで親ディレクトリのモジュールがimportできる
import upper
 
upper.upper_method()

実行結果

python lower.py

# current='<path>\\parentdir\\subdir'
# parent='<path>\\parentdir'
# Upper method

正常に親ディレクトリのモジュールがimportできた。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?