Python에서 절대 파일 경로를 얻는 방법
-
09-06-2019 - |
문제
다음과 같은 경로가 주어지면 "mydir/myfile.txt"
, Python에서 현재 작업 디렉터리를 기준으로 파일의 절대 경로를 어떻게 찾나요?예:Windows에서는 다음과 같이 끝날 수 있습니다.
"C:/example/cwd/mydir/myfile.txt"
해결책
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
이미 절대 경로인 경우에도 작동합니다.
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
다른 팁
새로운 Python 3.4 라이브러리를 사용할 수 있습니다. pathlib
.(다음을 사용하여 Python 2.6 또는 2.7용으로 얻을 수도 있습니다. pip install pathlib
.) 저자 썼다:"이 라이브러리의 목적은 파일 시스템 경로와 사용자가 이에 대해 수행하는 일반적인 작업을 처리하기 위한 간단한 클래스 계층 구조를 제공하는 것입니다."
Windows에서 절대 경로를 얻으려면:
>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'
또는 UNIX의 경우:
>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'
문서는 여기에 있습니다: https://docs.python.org/3/library/pathlib.html
>>> import os
>>> os.path.abspath('mydir/myfile.txt')
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
더 나은 방법은 모듈을 설치하는 것입니다. PyPI
), 모든 내용을 래핑합니다. os.path
함수 및 기타 관련 함수를 문자열이 사용되는 모든 곳에서 사용할 수 있는 객체의 메서드로 변환합니다.
>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
오늘은 다음을 사용할 수도 있습니다. unipath
기반으로 만들어진 패키지 path.py
: http://sluggo.scrapping.cc/python/unipath/
>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>
이 패키지를 사용하는 것이 좋습니다. 일반적인 os.path 유틸리티에 대한 깔끔한 인터페이스.
Python 3.4 이상용 업데이트 pathlib
실제로 질문에 대답합니다.
from pathlib import Path
relative = Path("mydir/myfile.txt")
absolute = relative.absolute() # absolute is a Path object
임시 문자열만 필요한 경우 다음을 사용할 수 있다는 점을 명심하세요. Path
관련된 모든 기능을 가진 객체 os.path
, 물론 포함해서 abspath
:
from os.path import abspath
absolute = abspath(relative) # absolute is a str object
import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))
참고하세요 expanduser
파일(또는 디렉터리) 이름과 위치에 대해 주어진 표현식에 선행 문자가 포함될 수 있는 경우 (Unix에서) 필요합니다. ~/
(물결표는 사용자의 홈 디렉토리를 나타냄) expandvars
다른 환경 변수(예: $HOME
).
나는 glob을 사용하는 것을 선호합니다
현재 폴더의 모든 파일 형식을 나열하는 방법은 다음과 같습니다.
import glob
for x in glob.glob():
print(x)
현재 폴더에 있는 모든 .txt 파일을 나열하는 방법은 다음과 같습니다.
import glob
for x in glob.glob('*.txt'):
print(x)
선택한 디렉토리의 모든 파일 형식을 나열하는 방법은 다음과 같습니다.
import glob
for x in glob.glob('C:/example/hi/hello/'):
print(x)
이것이 당신에게 도움이 되었기를 바랍니다
기준 치수 os
절대 경로를 찾는 방법을 제공합니다.
하지만 Linux의 대부분의 경로는 다음으로 시작합니다. ~
(물결표)는 만족스러운 결과를 제공하지 않습니다.
그래서 당신은 사용할 수 있습니다 srblib
그에 대한.
>>> import os
>>> os.path.abspath('~/hello/world')
'/home/srb/Desktop/~/hello/world'
>>> from srblib import abs_path
>>> abs_path('~/hello/world')
'/home/srb/hello/world'
사용하여 설치 python3 -m pip install srblib
당신이 맥을 사용하고 있다면
import os
upload_folder = os.path.abspath("static/img/users")
그러면 전체 경로가 제공됩니다.
print(upload_folder)
다음 경로가 표시됩니다.
>>>/Users/myUsername/PycharmProjects/OBS/static/img/user
누군가 Python과 Linux를 사용하고 파일의 전체 경로를 찾는 경우:
>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file
이것 언제나 다른 스크립트 내에서 호출되는 경우에도 현재 스크립트의 올바른 파일 이름을 가져옵니다.사용할 때 특히 유용합니다. subprocess
.
import sys,os
filename = sys.argv[0]
거기에서 다음을 사용하여 스크립트의 전체 경로를 얻을 수 있습니다.
>>> os.path.abspath(filename)
'/foo/bar/script.py'
또한 추가하기만 하면 폴더를 더 쉽게 탐색할 수 있습니다. /..
디렉토리 계층 구조에서 '위'로 이동하려는 횟수만큼.
CWD를 얻으려면:
>>> os.path.abspath(filename+"/..")
'/foo/bar'
상위 경로의 경우:
>>> os.path.abspath(filename+"/../..")
'/foo'
결합하여 "/.."
다른 파일 이름을 사용하면 시스템의 모든 파일에 액세스할 수 있습니다.
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"
filenameWithPath = os.path.join(filePathWithSlash, filename)