현재 파일의 디렉토리 경로를 가져오고 싶습니다. 나는 시도했다 :
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
그러나 디렉토리의 경로를 어떻게 검색 할 수 있습니까?
예를 들면 다음과 같습니다.
'C:\\python27\\'
답변
파이썬 3
실행중인 스크립트의 디렉토리 :
import pathlib
pathlib.Path(__file__).parent.absolute()
현재 작업 디렉토리의 경우 :
import pathlib
pathlib.Path().absolute()
파이썬 2와 3
실행중인 스크립트의 디렉토리 :
import os
os.path.dirname(os.path.abspath(__file__))
현재 작업 디렉토리를 의미하는 경우 :
import os
os.path.abspath(os.getcwd())
전후 file는 두 개의 밑줄이 아니라 하나의 밑줄입니다.
또한 대화식으로 실행 중이거나 파일 이외의 것 (예 : 데이터베이스 또는 온라인 리소스)에서 코드를로드 한 경우, __file__ “현재 파일”이라는 개념이 없으므로 설정되지 않을 수 있습니다. 위의 답변은 파일에있는 파이썬 스크립트를 실행하는 가장 일반적인 시나리오를 가정합니다.
참고 문헌
답변
PathPython 3부터 사용 하는 것이 좋습니다.
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute())
설명서 : pathlib
참고 : Jupyter Notebook을 사용하는 경우 __file__예상 값을 반환하지 않으므로 Path().absolute()사용해야합니다.
답변
Python 3.x에서는 다음을 수행합니다.
from pathlib import Path
path = Path(__file__).parent.absolute()
설명:
Path(__file__)현재 파일의 경로입니다..parent파일이 있는 디렉토리를 제공합니다 ..absolute()당신 에게 그것에 대한 완전한 절대 경로를 제공합니다.
pathlib경로를 사용 하는 현대적인 방법은 사용 입니다. 나중에 어떤 이유로 문자열로 필요하면 그냥하십시오 str(path).
답변
import os
print os.path.dirname(__file__)
답변
다음과 같이 쉽게 사용 os하고 os.path라이브러리 할 수 있습니다
import os
os.chdir(os.path.dirname(os.getcwd()))
os.path.dirname현재 디렉토리에서 상위 디렉토리를 반환합니다. 파일 인수를 전달하지 않고 절대 경로를 몰라도 상위 수준으로 변경할 수 있습니다.
답변
이 시도:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
답변
다음 명령이 모두 Python 3.6 스크립트의 부모 디렉토리의 전체 경로를 반환한다는 것을 알았습니다.
파이썬 3.6 스크립트 :
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 script
dir1 = Path().resolve() #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See @RonKalian answer
dir3 = Path(__file__).parent.absolute() #See @Arminius answer
print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}')
링크 설명 : .resolve () , .absolute () , Path ( file ..parent (). absolute ()
