MathPython
06 Sep 2024 20 Feb 2018

プログラムがある現在のディレクトリを取得する(Python)

現在のプログラムがあるディレクトリは 3 通りの方法で取得できます。

import os

a = os.path.curdir
b = os.path.abspath('.')
c = os.path.dirname(__file__)
d = os.getcwd()

print(a)
print(b)
print(c)
print(d)

出力

.
/python/code/system
/python/code/system
/python/code/system

上の結果はこのプログラムがあるディレクトリです。一番上の関数以外の3つはカレント・ディレクトリの絶対パスを返します。