LoginSignup
3
8

More than 5 years have passed since last update.

Pythonで親ディレクトリの絶対パスを取得

Last updated at Posted at 2018-04-28

自分が必要で少し時間かかったので(技術力不足)共有します
特に説明する事もないので簡単に
子のファイルと、上に戻るディレクトリ階層の指定を引数に与える事ができます

ソース

  • osを使ったもの
import os

def parentpath(path=__file__, f=0):
    return str('/'.join(os.path.abspath(path).split('/')[0:-1-f])))
  • pathlibを使ったもの (4/29 コメントで教えていただきありがとうございます!)
from pathlib import Path

def parentpath(path='.', f=0):
    return Path(path).resolve().parents[f]

使い方

#currentdir /Users/you/repository/test/pro/source/app/api/cruc.py

print(parentpath(__file__,0))#->/Users/you/repository/test/pro/source/app/api/
print(parentpath(__file__,1))#->/Users/you/repository/test/pro/source/app/
print(parentpath(__file__,2))#->/Users/you/repository/test/pro/source/
print(parentpath(__name__,0))#->/Users/you/repository/test/pro/source/app/
print(parentpath(__name__,1))#->/Users/you/repository/test/pro/source/
3
8
3

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
3
8