何かとややこしいPythonのパス参照をまとめました。コピペが捗りますね。
(※使う時はosモジュールのインポートが必要です)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# 実行ファイルの相対パス(=実行ファイル名) __file__ # 実行ファイルの絶対パス os.path.abspath(__file__) # OS上のカレントディレクトリの絶対パス os.getcwd() # 実行ファイルの親ディレクトリの相対パス(=親ディレクトリ名) os.path.basename(os.path.dirname(os.path.abspath(__file__))) # 実行ファイルの親ディレクトリの絶対パス os.path.dirname(os.path.abspath(__file__)) # 引数(絶対パス)の親ディレクトリの相対パスを取得 os.path.basename(os.path.dirname(_path)) # 引数(絶対パス)の親ディレクトリの絶対パスを取得 os.path.dirname(_path) # 絶対パスから相対パスに変換 os.path.basename(_path) # 相対パスから絶対パスに変換 os.path.abspath(_path) |
例えば、
1 |
print(os.path.abspath(__file__)) |
で実行ファイルの絶対パスが表示できます。
コメント