LoginSignup
67

More than 5 years have passed since last update.

[Python] スクリプト実行ディレクトリを絶対パスで取得する

Posted at

ずばり、以下で取得可能。

os.path.dirname(os.path.abspath(__file__))

動作確認用のテストコード

get_abs_dirname.py
import os

print("__file__                                  : %r" %  __file__)
print("os.path.dirname(__file__)                 : %r" % (os.path.dirname(__file__)))
print("os.path.abspath(__file__)                 : %r" % (os.path.abspath(__file__)))
print("os.path.dirname(os.path.abspath(__file__)): %r" % (os.path.dirname(os.path.abspath(__file__))))
実行結果
__file__                                  : 'get_abs_dirname.py'
os.path.dirname(__file__)                 : ''
os.path.abspath(__file__)                 : '/home/nagamee/work/get_abs_dirname.py'
os.path.dirname(os.path.abspath(__file__)): '/home/nagamee/work/'

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
67