LoginSignup
15
13

More than 5 years have passed since last update.

実行しているファイルが格納されているディレクトリのパスを取得したい。

Last updated at Posted at 2017-07-25

タイトル通り、実行したファイルが格納されているディレクトリのパスを取得したいという場合、Python3ではどのように書くべきでしょうか? まずはos.pathを利用する場合。取得パスが相対パスでよいというときは次のように書きます。

import os.path
directory = os.path.dirname(__file__)

相対パスではなく、絶対パスがほしい場合は次の通りです。

import os.path
directory = os.path.dirname(os.path.abspath(__file__))

次にファイルパスを抽象化したクラスであるpathlib.Pathを利用する場合を考えます(os.pathではファイルパスを文字列で扱う)。

まずは相対パスの場合。

import pathlib
directory = pathlib.Path(__file__).parent

次に絶対パス。

import pathlib
directory = pathlib.Path(__file__).parent.resolve()

os.pathにしろpathlibにしろ、とてもシンプルに書けますね(´・ω・`)

15
13
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
15
13