IT이야기

현재 파일 디렉터리의 전체 경로를 가져오는 방법

cyworld 2022. 4. 9. 08:56
반응형

현재 파일 디렉터리의 전체 경로를 가져오는 방법

현재 파일의 디렉터리 경로를 가져오려고 함.나는 노력했다:

>>> os.path.abspath(__file__)
'C:\\python27\\test.py'

그런데 어떻게 하면 디렉토리의 경로를 검색할 수 있을까?

예를 들면 다음과 같다.

'C:\\python27\\'

특수 변수에는 현재 파일의 경로가 포함되어 있다.여기서 Pathlib 또는 os.path 모듈을 사용하여 디렉토리를 가져올 수 있다.

파이톤 3

실행 중인 스크립트의 디렉터리인 경우:

import pathlib
pathlib.Path(__file__).parent.resolve()

현재 작업 디렉토리의 경우:

import pathlib
pathlib.Path().resolve()

파이톤 2와 3

실행 중인 스크립트의 디렉터리인 경우:

import os
os.path.dirname(os.path.abspath(__file__))

현재 작업 디렉터리를 의미하는 경우:

import os
os.path.abspath(os.getcwd())

전후에 주의하십시오.file하나의 밑줄이 아니라 두 개의 밑줄이다.

또한 대화형으로 실행 중이거나 파일이 아닌 다른 것(예: 데이터베이스 또는 온라인 리소스)에서 코드를 로드한 경우,__file__"현재 파일"이라는 개념이 없기 때문에 설정되지 않을 수 있다.위의 답변은 파일에 있는 파이선 스크립트를 실행하는 가장 일반적인 시나리오를 가정한다.

참조

  1. pathlib(파이톤) 설명서의 pathlib.
  2. os.path - Python 2.7, os.path - Python 3
  3. os.getcwd - Python 2.7, os.getcwd - Python 3
  4. __file__ 변수의 의미는 무엇인가?

사용.PathPython 3 이후 권장되는 방법:

from pathlib import Path
print("File      Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__  

설명서: pathlib

참고: Juffyter 노트북을 사용할 경우__file__기대치를 반환하지 않기 때문에Path().absolute()사용되어야 한다.

Python 3.x에서 나는 다음을 한다.

from pathlib import Path

path = Path(__file__).parent.absolute()

설명:

  • Path(__file__)현재 파일의 경로.
  • .parent파일이 있는 디렉토리를 제공하십시오.
  • .absolute()완벽한 길을 열어주지

사용.pathlib길과 함께 일하는 현대적인 방법이다.나중에 어떤 이유로 끈으로 필요하면 그냥 해.str(path).

다음을 시도해 보십시오.

import os
dir_path = os.path.dirname(os.path.realpath(__file__))
import os
print os.path.dirname(__file__)

나는 다음 명령들이 Python 3 스크립트의 부모 디렉토리의 전체 경로를 반환하는 것을 발견했다.

Python 3 스크립트:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from pathlib import Path

#Get the absolute path of a Python3.6 and above 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
dir4 = Path(__file__).parent 

print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}\ndir4={dir4}')

비고 !!!!!

  1. dir1그리고dir2현재 작업 디렉토리에 있는 스크립트를 실행할 때만 작동하지만 다른 경우에는 중단된다.
  2. 그런 것을 감안한다면Path(__file__).is_absolute()이다True, 의 사용.absolute()dir3의 방법은 중복된 것으로 보인다.
  3. 가장 짧은 명령은 dir4이다.

설명 링크: .resolve(), .absolute(), Path(파일)parent(.parents.parents)

IPython마법의 명령이 있다.%pwd현재 작업 디렉토리를 가져오십시오.다음과 같은 방법으로 사용할 수 있다.

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

IPython Juffyter 노트북에서%pwd다음과 같이 직접 사용할 수 있다.

present_working_directory = %pwd

파이썬의 유용한 경로 속성:

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

출력: 절대 경로는 Python 파일이 배치되는 경로임

절대 경로 : D:\Study\Machine Learning\주피터 노트북\주피토르노트북Test2\Udacity_Scripts\Matplotlib 및 seaorn Part2

파일 경로 : D:\Study\Machine Learning\주피터 노트북\주피토르노트북테스트2\Udacity_Scripts\Matplotlib 및 Seaborn Part2\data\fuel_econ.csv

isfileExist : True

Isadirectory : Fal

파일 확장명 : .csv

현재 폴더를 가져오기 위해 CGI에서 IIS에서 python을 실행할 때 사용할 수 있는 기능을 만들었다.

import os 
def getLocalFolder():
    path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
    return path[len(path)-1]

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

반응형