programing tip

현재 파일 디렉토리의 전체 경로를 어떻게 얻습니까?

itbloger 2020. 10. 2. 21:47
반응형

현재 파일 디렉토리의 전체 경로를 어떻게 얻습니까?


현재 파일의 디렉토리 경로를 얻고 싶습니다. 나는 시도했다 :

>>> 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

참고URL : https://stackoverflow.com/questions/3430372/how-do-i-get-the-full-path-of-the-current-files-directory

반응형