현재 파일 디렉토리의 전체 경로를 어떻게 얻습니까?
현재 파일의 디렉토리 경로를 얻고 싶습니다. 나는 시도했다 :
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
그러나 디렉토리 경로를 어떻게 검색 할 수 있습니까?
예를 들면 :
'C:\\python27\\'
실행중인 스크립트의 디렉토리를 의미하는 경우 :
import os
os.path.dirname(os.path.abspath(__file__))
현재 작업 디렉토리를 의미하는 경우 :
import os
os.getcwd()
이전과 이후 file
는 하나가 아니라 두 개의 밑줄입니다.
또한 대화 형으로 실행 중이거나 파일이 아닌 다른 것 (예 : 데이터베이스 또는 온라인 리소스)에서 코드를로드 한 경우 __file__
"현재 파일"이라는 개념이 없기 때문에 설정되지 않을 수 있습니다. 위의 답변은 파일에있는 파이썬 스크립트를 실행하는 가장 일반적인 시나리오를 가정합니다.
사용 Path
은 Python 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
현재 디렉토리에서 상위 디렉토리를 반환합니다. 파일 인수를 전달하지 않고 절대 경로를 몰라도 상위 수준으로 변경할 수 있습니다.
IPython
%pwd
현재 작업 디렉토리를 가져 오는 마법의 명령 이 있습니다. 다음과 같은 방법으로 사용할 수 있습니다.
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
On IPython Jupyter Notebook %pwd
can be used directly as following:
present_working_directory = %pwd
Try this:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
To keep the migration consistency across platforms (macOS/Windows/Linux), try:
path = r'%s' % os.getcwd().replace('\\','/')
I have made a function to use when running python under IIS in CGI in order to get the current folder:
import os
def getLocalFolder():
path=str(os.path.dirname(os.path.abspath(__file__))).split('\\')
return path[len(path)-1]
System: MacOS
Version: Python 3.6 w/ Anaconda
import os rootpath = os.getcwd() os.chdir(rootpath)
USEFUL PATH PROPERTIES IN PYTHON:
from pathlib import Path
#Returns the path of the directory, where your script file is placed
mypath = Path().absolute()
print('Absolute path : {}'.format(mypath))
#if you want to go to any other file inside the subdirectories of the directory path got from above method
filePath = mypath/'data'/'fuel_econ.csv'
print('File path : {}'.format(filePath))
#To check if file present in that directory or Not
isfileExist = filePath.exists()
print('isfileExist : {}'.format(isfileExist))
#To check if the path is a directory or a File
isadirectory = filePath.is_dir()
print('isadirectory : {}'.format(isadirectory))
#To get the extension of the file
fileExtension = mypath/'data'/'fuel_econ.csv'
print('File extension : {}'.format(filePath.suffix))
OUTPUT: ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED
Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2
File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv
isfileExist : True
isadirectory : False
File extension : .csv
## IMPORT MODULES
import os
## CALCULATE FILEPATH VARIABLE
filepath = os.path.abspath('') ## ~ os.getcwd()
## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
## ..OR DIFFERENT IN SOME CIRCUMSTANCES
'programing tip' 카테고리의 다른 글
다른 쉘 스크립트에서 쉘 스크립트를 호출하는 방법은 무엇입니까? (0) | 2020.10.02 |
---|---|
값이 null 인 경우 직렬화 중에 Jackson에게 필드를 무시하도록 지시하는 방법은 무엇입니까? (0) | 2020.10.02 |
원격에 더 이상 존재하지 않는 로컬 추적 분기를 정리하는 방법 (0) | 2020.10.02 |
문자열로 끝나는 href (0) | 2020.10.02 |
bat 파일을 통해 Windows를 종료, 다시 시작 또는 로그 오프하려면 어떻게합니까? (0) | 2020.10.02 |