여러 오픈 소스 프로젝트에서 사람들이 os.path.abspath(os.path.realpath(__file__))현재 파일의 절대 경로를 얻는 것을 보았습니다 .
그러나, 나는 그것을 찾을 수 os.path.abspath(__file__)와 os.path.realpath(__file__)동일한 결과를 생성합니다. os.path.abspath(os.path.realpath(__file__))약간 중복되는 것 같습니다.
사람들이 그것을 사용하는 이유가 있습니까?
답변
os.path.realpath 이를 지원하는 운영 체제에서 심볼릭 링크를 무시합니다.
os.path.abspath단순히 디렉토리 트리의 루트에서 명명 된 파일 (또는 심볼릭 링크)까지의 전체 경로를 제공하는 경로 .와 같은 것을 제거합니다...
예를 들어 Ubuntu에서
$ ls -l
total 0
-rw-rw-r-- 1 guest guest 0 Jun 16 08:36 a
lrwxrwxrwx 1 guest guest 1 Jun 16 08:36 b -> a
$ python
Python 2.7.11 (default, Dec 15 2015, 16:46:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from os.path import abspath, realpath
>>> abspath('b')
'/home/guest/play/paths/b'
>>> realpath('b')
'/home/guest/play/paths/a'
Symlink는 상대 경로를 포함 할 수 있으므로 둘 다 사용해야합니다. 에 대한 내부 호출 realpath은 포함 된 ..부분이 있는 경로를 반환 한 abspath다음 제거 할 수 있습니다.
답변
명시된 시나리오의 경우 os.path.realpath실제로 os.path.abspath결과를 반환하기 전에 호출 하기 때문에 realpath와 abspath를 결합 할 이유가 없습니다 (Python 2.5에서 Python 3.6으로 확인).
os.path.abspath절대 경로를 반환하지만 인수에서 심볼릭 링크를 확인하지 않습니다.os.path.realpath먼저 경로의 모든 심볼릭 링크를 확인한 다음 절대 경로를 반환합니다.
당신이 당신의 경로가 포함되어 기대하는 경우에는 ~, abspath 또는 realpath 어느 쪽도 해결할 수 ~사용자의 홈 디렉토리에 생성 된 경로가 잘못 될 것입니다 . os.path.expanduser이 문제를 사용자 디렉터리로 확인하려면를 사용해야 합니다.
철저한 설명을 위해 Windows 및 Linux, Python 3.4 및 Python 2.6에서 확인한 몇 가지 결과가 있습니다. 현재 디렉토리 ( ./)는 다음과 같은 내 홈 디렉토리입니다.
myhome
|- data (symlink to /mnt/data)
|- subdir (extra directory, for verbose explanation)
# os.path.abspath returns the absolute path, but does NOT resolve symlinks in its argument
os.path.abspath('./')
'/home/myhome'
os.path.abspath('./subdir/../data')
'/home/myhome/data'
# os.path.realpath will resolve symlinks AND return an absolute path from a relative path
os.path.realpath('./')
'/home/myhome'
os.path.realpath('./subdir/../')
'/home/myhome'
os.path.realpath('./subdir/../data')
'/mnt/data'
# NEITHER abspath or realpath will resolve or remove ~.
os.path.abspath('~/data')
'/home/myhome/~/data'
os.path.realpath('~/data')
'/home/myhome/~/data'
# And the returned path will be invalid
os.path.exists(os.path.abspath('~/data'))
False
os.path.exists(os.path.realpath('~/data'))
False
# Use realpath + expanduser to resolve ~
os.path.realpath(os.path.expanduser('~/subdir/../data'))
'/mnt/data'
답변
평범한 용어로 바로 가기 파일의 경로를 얻으려는 경우 절대 경로는 바로 가기 위치 에있는 파일의 전체 경로를 제공하는 반면 realpath는 파일 의 원래 위치 경로를 제공 합니다.
절대 경로 os.path.abspath ()는 현재 작업 디렉토리 또는 언급 한 디렉토리에있는 파일의 전체 경로를 제공합니다.
실제 경로 os.path.realpath ()는 참조되는 파일의 전체 경로를 제공합니다.
예 :
file = "shortcut_folder/filename"
os.path.abspath(file) = "C:/Desktop/shortcut_folder/filename"
os.path.realpath(file) = "D:/PyCharmProjects/Python1stClass/filename"
