68
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

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

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

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 can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
68
Help us understand the problem. What are the problem?