파이썬

[python] 현재 디렉토리와 파일의 디렉토리 찾기 [중복]

zooheon 2022. 8. 28. 20:16
반응형

어떻게 결정합니까?

  1. 현재 디렉토리(Python 스크립트를 실행할 때 터미널에 있었던 위치) 및
  2. 내가 실행하는 Python 파일은 어디에 있습니까?

 

Python 파일이 포함된 디렉토리의 전체 경로를 얻으려면 해당 파일에 다음을 작성하십시오.

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

( 상수 값은 현재 작업 디렉토리에 상대적이고 호출에 의해 변경되지 않기 os.chdir()때문에 현재 작업 디렉토리를 변경 하는 데 이미 사용했다면 위의 주문은 작동 하지 않습니다 .)__file__os.chdir()


현재 작업 디렉토리를 얻으려면 다음을 사용하십시오.

import os
cwd = os.getcwd()

위에서 사용된 모듈, 상수 및 함수에 대한 문서 참조:

 

현재 작업 디렉토리 : os.getcwd()

그리고 __file__속성 은 실행 중인 파일의 위치를 ​​찾는 데 도움이 될 수 있습니다. 이 스택 오버플로 게시물은 모든 것을 설명합니다 . Python에서 현재 실행된 파일의 경로를 얻으려면 어떻게 해야 합니까?

 

참조로 유용할 수 있습니다.

import os

print("Path at terminal when executing this file")
print(os.getcwd() + "\n")

print("This file path, relative to os.getcwd()")
print(__file__ + "\n")

print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")

print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "\n")

print("This file directory only")
print(os.path.dirname(full_path))

 

반응형