I want to get 현재 file& # 39 의 디렉터리 경로. 내가 시도했다.
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
그러나 directory& 읽어들입니다 # 39 의 경로를 어떻게 해야 합니까?
예를 들면 다음과 같습니다.
'C:\\python27\\'
이 경우 디렉터리이고 스크립트입니다 실행하십시오 짓궂군요 있다.
import os
os.path.dirname(os.path.abspath(__file__))
짓궂군요 경우 현재 작업 디렉터리입니다.
import os
os.getcwd()
참고로 전 / 후 파일 '가 아니라' 2 밑줄 하나.
또한 대화식으로 있거나 로드됨 코드에서 실행하는 경우 이외의 파일 (예: 데이터베이스 또는 온라인 리소스) 을 설정할 수 없습니다 'file' 의 개념이 없기 때문에, 현재의 " file". 가장 일반적인 경우 위의 오토메이티드 는 파이썬 스크립트입니다 실행 파일에.
이후 '길' 은 권장됨 방법을 사용하여 파이썬 3:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute())
문서: [파트리브] (https://docs.python.org/3/library/pathlib.html)
참고: # 39, t ',' file 주피터 노트북 사용할 경우 doesn& 복귀하십시오 이바솔우테 예상값 도왔으매 '경로 () ()' 에 사용할 수 있습니다.
윈도 3.x 에서 나는한다:
from pathlib import Path
path = Path(__file__).parent.absolute()
설명:
'현대' 이 방법을 사용하여 파트리브 작동합니까 패스. Just do it as a string str, 나중에 필요한 경우 어떤 이유로 ' (경로)'.
'현재' 명령 '매직' 은 이피통 %pwd afaq apc® 디렉터리입니다. 다음과 같은 방법으로 사용할 수 있습니다.
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
'노트북' 에서 다음과 같이 이피통 주피터 %pwd 직접 사용할 수 있습니다.
present_working_directory = %pwd
유용한 PATH 속성을 파이썬.
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))
절대 경로: Part2 시본 d:\study\machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib 및
파일 경로: D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib 및 시본 Part2\data\fuel_econ.csv
이스피리시스트: 진정한
이드리스토리: 거짓값
파일 확장자. .csv
내가 찾은 다음 명령을 실행하면 상위입니다 디렉터리이고 귀의하리니 전체 경로) 는 파이썬 3.6tb 스크립트입니다.
#!/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}')
설명 링크: [그레솔베 ()] [1], 이바솔우테 (), 경로 (file) 이바솔우테 자파렌트 () ()
[1]: https://docs.python.org/3.6/library/pathlib.html = 파트리브 # 파트리발파트리어솔베 강조표시할?
마이그레이션과 일관성을 유지하기 위해 플랫폼 (macOS / Windows / Linux), 종료기:
path = r'%s' % os.getcwd().replace('\\','/')
## 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