os.path.sysname(__file_)이(가) 비어 있음을 반환합니다.
.py 파일이 실행되는 현재 디렉터리의 경로를 알고 싶습니다.
예를 들어 단순 파일D:\test.py
코드 포함:
import os
print os.getcwd()
print os.path.basename(__file__)
print os.path.abspath(__file__)
print os.path.dirname(__file__)
출력이 다음과 같은 것이 이상합니다.
D:\
test.py
D:\test.py
EMPTY
나는 같은 결과를 기대하고 있습니다.getcwd()
그리고.path.dirname()
.
정해진os.path.abspath = os.path.dirname + os.path.basename
,왜죠
os.path.dirname(__file__)
반환이 비어 있습니까?
왜냐면os.path.abspath = os.path.dirname + os.path.basename
보유하지 않습니다. 우리는 오히려 보유하고 있습니다.
os.path.dirname(filename) + os.path.basename(filename) == filename
둘다요.dirname()
그리고.basename()
현재 디렉터리를 고려하지 않고 전달된 파일 이름만 구성 요소로 분할합니다.현재 디렉토리도 고려하려면 명시적으로 고려해야 합니다.
절대 경로의 dir 이름을 가져오려면 다음을 사용합니다.
os.path.dirname(os.path.abspath(__file__))
import os.path
dirname = os.path.dirname(__file__) or '.'
os.path.split(os.path.realpath(__file__))[0]
os.path.realpath(__file__)
현재 스크립트의 abspath를 반환합니다. os.path.dll(abspath)[0] 현재 dir를 반환합니다.
다음과 같이 사용할 수도 있습니다.
dirname(dirname(abspath(__file__)))
print(os.path.join(os.path.dirname(__file__)))
이 방법을 사용할 수도 있습니다.
Python 3.4부터는pathlib
현재 디렉터리를 가져오는 방법:
from pathlib import Path
# get parent directory
curr_dir = Path(__file__).parent
file_path = curr_dir.joinpath('otherfile.txt')
위의 답변 중 정답이 없습니다.OP는 저장되지 않고 .py 파일이 실행되는 현재 디렉터리의 경로를 가져오려고 합니다.
따라서 이 파일의 경로가/opt/script.py
...
#! /usr/bin/env python3
from pathlib import Path
# -- file's directory -- where the file is stored
fd = Path(__file__).parent
# -- current directory -- where the file is executed
# (i.e. the directory of the process)
cwd = Path.cwd()
print(f'{fd=} {cwd=}')
이 스크립트를 실행하는 경우에만/opt
,fd
그리고.cwd
동일할 것입니다.
$ cd /
$ /opt/script.py
cwd=PosixPath('/') fd=PosixPath('/opt')
$ cd opt
$ ./script.py
cwd=PosixPath('/opt') fd=PosixPath('/opt')
$ cd child
$ ../script.py
cwd=PosixPath('/opt/child') fd=PosixPath('/opt/child/..')
이것은 os 모듈이 없는 간단한 코드인 것 같습니다.
__file__.split(__file__.split("/")[-1])[0]
언급URL : https://stackoverflow.com/questions/7783308/os-path-dirname-file-returns-empty
'programing' 카테고리의 다른 글
mLab에서 MongoDB 데이터베이스에 연결하면 인증에 실패함 (0) | 2023.07.04 |
---|---|
web.xml을 사용하여 스프링 부트 응용 프로그램 구성 (0) | 2023.07.04 |
MongoDB가 쿼리에 대해 인증되지 않음 - 코드 13 (0) | 2023.07.04 |
문서 데이터베이스:중복 데이터, 참조 자료 등(특히 MongoDB) (0) | 2023.07.04 |
데이터베이스의 보기를 업데이트할 수 있습니까? (0) | 2023.07.04 |