IT박스

부모 디렉토리 위치를 얻는 방법

itboxs 2020. 7. 12. 10:23
반응형

부모 디렉토리 위치를 얻는 방법


이 코드는 b.py에서 templates / blog1 / page.html을 얻습니다.

path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))

하지만 부모 디렉토리 위치를 얻고 싶습니다.

aParent
   |--a
   |  |---b.py
   |      |---templates
   |              |--------blog1
   |                         |-------page.html
   |--templates
          |--------blog1
                     |-------page.html

부모의 위치를 ​​얻는 방법

감사

업데이트 :

이것은 맞다 :

dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))

또는

path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))

dirname을 반복해서 적용하여 더 높아질 수 있습니다 dirname(dirname(file)).. 그러나 이것은 루트 패키지까지만 가능합니다. 이것이 문제인 경우 다음을 사용 os.path.abspath하십시오 dirname(dirname(abspath(file)))..


os.path.abspath아무것도 확인하지 않으므로 이미 문자열을 추가하는 __file__경우 귀찮 dirname거나 조인 할 필요가 없습니다 . __file__디렉토리로 취급 하고 등반을 시작하십시오.

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

그보다 os.path.abspath(os.path.join(os.path.dirname(__file__),".."))관리하기 가 훨씬 복잡 dirname(dirname(__file__))합니다. 두 단계 이상의 등반은 말도 안되게 시작됩니다.

그러나 얼마나 많은 레벨을 올라갈 지 알기 때문에 간단한 작은 기능으로 이것을 정리할 수 있습니다.

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'

Python 3.4 이상 에서 모듈 상대 경로사용하십시오 pathlib.

from pathlib import Path

Path(__file__).parent

여러 통화를 사용 parent하여 경로를 더 진행할 수 있습니다 .

Path(__file__).parent.parent

parent두 번 지정하는 대신 다음을 사용할 수 있습니다.

Path(__file__).parents[1]

os.path.dirname(os.path.abspath(__file__))

경로를 알려줘야합니다 a.

그러나 b.py현재 실행중인 파일 인 경우 다음을 수행하여 동일한 결과를 얻을 수 있습니다

os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))

os.pardir../더 읽기 쉽고 읽기 쉬운 방법입니다 .

import os
print os.path.abspath(os.path.join(given_path, os.pardir))  

given_path의 부모 경로를 반환합니다


간단한 방법은 다음과 같습니다.

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

..부모 폴더의 부모를 얻기 위해 두 폴더에 가입 할 수 있습니까?

path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))

다음을 사용하여 이전 폴더로 이동하십시오.

os.chdir(os.pardir)

여러 번 점프 해야하는 경우 좋고 쉬운 해결책은이 경우 간단한 데코레이터를 사용하는 것입니다.


다음은 비교적 간단한 또 ​​다른 솔루션입니다.

  • does not use dirname() (which does not work as expected on one level arguments like "file.txt" or relative parents like "..")
  • does not use abspath() (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths

it just uses normpath and join:

def parent(p):
    return os.path.normpath(os.path.join(p, os.path.pardir))

# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
        'dir/file.txt', '../up/', '/abs/path']:
    print parent(p)

Result:

.
foo/bar
with/trailing
dir
..
/abs

I think use this is better:

os.path.realpath(__file__).rsplit('/', X)[0]


In [1]: __file__ = "/aParent/templates/blog1/page.html"

In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'

In [4]: __file__ = "/aParent/templates/blog1/page.html"

In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'

In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'

In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'

I tried:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))

참고URL : https://stackoverflow.com/questions/2817264/how-to-get-the-parent-dir-location

반응형