development

파이썬 : 디렉토리를 두 ​​단계 위로 가져 오기

big-blog 2020. 12. 3. 08:09
반응형

파이썬 : 디렉토리를 두 ​​단계 위로 가져 오기


좋아 ... 모듈 x어디에 있는지 모르겠지만 디렉토리 경로를 두 단계 위로 가져와야한다는 것을 알고 있습니다.

따라서 더 우아한 방법이 있습니까?

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

Python 2와 3 모두에 대한 솔루션을 환영합니다!


사용할 수 있습니다 pathlib. 불행히도 이것은 Python 3.4 용 stdlib에서만 사용할 수 있습니다. 이전 버전이있는 경우 여기 에서 PyPI 사본을 설치해야합니다 . 을 사용하면 쉽게 할 수 pip있습니다.

from pathlib import Path

p = Path(__file__).parents[1]

print(p)
# /absolute/path/to/two/levels/up

이것은 parents상위 디렉토리에 대한 액세스를 제공하고 두 번째 디렉토리를 선택 하는 시퀀스를 사용합니다 .

참고 p이 경우 어떤 형태가 될 것입니다 Path자신의 방법으로, 객체입니다. 문자열로 경로가 필요한 경우 호출 할 수 str있습니다.


아주 쉽게:

원하는 것은 다음과 같습니다.

import os.path as path

two_up =  path.abspath(path.join(__file__ ,"../.."))

감사합니다 Sebi


나는 이것을 단지 어리석게하기 위해 추가하려고했지만, 이것은 또한 새로운 사람들에게 앨리어싱 함수 및 / 또는 가져 오기의 잠재적 인 유용성을 보여주기 때문입니다.

그것을 작성하면이 코드가 현재까지 다른 답변보다 더 읽기 쉽고 (즉 의도를 파악하는 데 더 적은 시간) 가독성이 (일반적으로) 왕이라고 생각합니다.

from os.path import dirname as up

two_up = up(up(__file__))

참고 : 모듈이 매우 작거나 상황에 따라 응집력이있는 경우에만 이런 종류의 작업을 수행합니다.


디렉토리 2 레벨을 올리려면 :

 import os.path as path
 two_up = path.abspath(path.join(os.getcwd(),"../.."))

모든 디렉토리에서 실행할 때 가장 좋은 솔루션 (python> = 3.4)은 다음과 같습니다.

from pathlib import Path
two_up = Path(__file__).resolve().parents[1]

개인적으로 os 모듈을 사용하는 것이 아래에 설명 된 가장 쉬운 방법이라는 것을 알았습니다. 한 단계 만 올라가는 경우 ( '../ ..')를 ( '..')로 바꿉니다.

    import os
    os.chdir('../..')

--Check:
    os.getcwd()

2.7.x에서 다음이 잘 작동 함을 발견했습니다.

import os
two_up = os.path.normpath(os.path.join(__file__,'../'))

이것을 일반적인 솔루션으로 사용할 수 있습니다.

import os

def getParentDir(path, level=1):
  return os.path.normpath( os.path.join(path, *([".."] * level)) )

더 많은 크로스 플랫폼 구현은 다음과 같습니다.

import pathlib
two_up = (pathlib.Path(__file__) / ".." / "..").resolve()

Using parent is not supported on Windows. Also need to add .resolve(), to:

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows)


I don't yet see a viable answer for 2.7 which doesn't require installing additional dependencies and also starts from the file's directory. It's not nice as a single-line solution, but there's nothing wrong with using the standard utilities.

import os

grandparent_dir = os.path.abspath(  # Convert into absolute path string
    os.path.join(  # Current file's grandparent directory
        os.path.join(  # Current file's parent directory
            os.path.dirname(  # Current file's directory
                os.path.abspath(__file__)  # Current file path
            ),
            os.pardir
        ),
        os.pardir
    )
)

print grandparent_dir

And to prove it works, here I start out in ~/Documents/notes just so that I show the current directory doesn't influence outcome. I put the file grandpa.py with that script in a folder called "scripts". It crawls up to the Documents dir and then to the user dir on a Mac.

(testing)AlanSE-OSX:notes AlanSE$ echo ~/Documents/scripts/grandpa.py 
/Users/alancoding/Documents/scripts/grandpa.py
(testing)AlanSE-OSX:notes AlanSE$ python2.7 ~/Documents/scripts/grandpa.py 
/Users/alancoding

This is the obvious extrapolation of the answer for the parent dir. Better to use a general solution than a less-good solution in fewer lines.

참고URL : https://stackoverflow.com/questions/27844088/python-get-directory-two-levels-up

반응형