LoginSignup
4
8

More than 5 years have passed since last update.

PythonでPATHを取得する

Last updated at Posted at 2019-04-19

前提

windows10
実行ファイル名:test.py
ディレクトリ構成:C:\Dev\hoge\test.py

実行ファイル含めた絶対PATHを取得するとき

os.path.abspath(__file__)
>>> C:\Dev\hoge\test.py

実行ファイルのディレクトリへの絶対PATHを取得するとき

import os
pwd = os.getcwd()
os.path.abspath(pwd)
>>> C:\Dev\hoge

もしくは

os.path.dirname(os.path.abspath("__file__"))
>>> C:\Dev\hoge

dirname, basename, abspathについて

os.path.dirname()

os.path.dirname(__file__)
>>> C:\Dev\hoge

os.path.dirname(__pwd__)
>>> C:\Dev

os.path.basename()

os.path.basename(__file__)
>>> test.py

os.path.basename(__pwd__)
>>> hoge

os.path.abspath()

os.path.basename(__file__)
>>> C:\Dev\hoge\test.py

os.path.basename(__pwd__)
>>> C:\Dev\hoge

実行ファイル名を取得するとき

pathではないのですが、メモとして...

os.path.basename(__file__)
>>> test.py
a = __file__
print(a)
>>> test.py
4
8
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
4
8