현재 디렉토리 및 파일의 디렉토리 찾기 [복제]


질문

 

파이썬에서는 다음을 찾을 수있는 명령을 사용할 수 있습니다.

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the file I am executing is?

답변

 

디렉토리에 전체 경로를 얻으려면 파이썬 파일이 포함되어 있으므로이 파일에이를 씁니다.

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

(__file__ 상수의 값이 현재 작업 디렉토리와 관련이 있으므로 현재 작업 디렉토리를 이미 변경하기 때문에 이미 os.chdir ()을 변경하면 위의 incantation이 작동하지 않습니다.chdir () 호출.)


현재 작업 디렉토리 사용을 얻으려면

import os
cwd = os.getcwd()

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

OS 및 OS.Path 모듈. __file__ 상수 os.path.RealPath (경로) (지정된 파일 이름의 표준 경로를 반환하므로 경로에서 발생한 기호 링크가 발생하지 않음) os.path.dirname (경로) ( "pathname 경로의 디렉토리 이름"을 반환합니다) os.getCWD () (현재 작업 디렉토리를 나타내는 문자열 "을 반환합니다) os.chdir (경로) ( "현재 작업 디렉토리를 경로로 변경")



답변

현재 작업 디렉토리 : 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))


답변

파이썬 3.4 (PEP 428 - PathLib 모듈 - 객체 지향 파일 시스템 경로)에 도입 된 PathLib 모듈은 경로 관련 경험을 훨씬 더 훨씬 잘 만듭니다.

pwd

/home/skovorodkin/stack

tree

.
└── scripts
    ├── 1.py
    └── 2.py

현재 작업 디렉토리를 가져 오려면 path.cwd ()를 사용하십시오.

from pathlib import Path

print(Path.cwd())  # /home/skovorodkin/stack

스크립트 파일에 대한 절대 경로를 얻으려면 path.resolve () 메소드를 사용하십시오.

print(Path(__file__).resolve())  # /home/skovorodkin/stack/scripts/1.py

그리고 스크립트가있는 디렉토리의 경로를 가져 오려면 .parent에 액세스하십시오.

print(Path(__file__).resolve().parent)  # /home/skovorodkin/stack/scripts

일부 상황에서는 __file__이 안정적이지 않습니다. Python에서 현재 실행 된 파일의 경로를 얻는 방법은 무엇입니까?


Please note, that Path.cwd(), Path.resolve() and other Path methods return path objects (PosixPath in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open built-in function could only work with string or bytes objects, and did not support Path objects, so you had to convert Path objects to strings or use the Path.open() method, but the latter option required you to change old code:

File scripts/2.py

from pathlib import Path

p = Path(__file__).resolve()

with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass

print('OK')

Output

python3.5 scripts/2.py

Traceback (most recent call last):
  File "scripts/2.py", line 11, in <module>
    with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')

As you can see, open(p) does not work with Python 3.5.

PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike objects to the open function, so now you can pass Path objects to the open function directly:

python3.6 scripts/2.py

OK


답변

  1. To get the current directory full path

    >>import os
    >>print os.getcwd()
    

    Output: "C :\Users\admin\myfolder"

  2. To get the current directory folder name alone

    >>import os
    >>str1=os.getcwd()
    >>str2=str1.split('\\')
    >>n=len(str2)
    >>print str2[n-1]
    

    Output: "myfolder"



답변

현재 스크립트가 들어있는 디렉토리를 가져 오는이 방법으로 PathLib을 사용할 수 있습니다.

import pathlib
filepath = pathlib.Path(__file__).resolve().parent
출처:https://stackoverflow.com/questions/5137497/find-the-current-directory-and-files-directory