os.path — 일반적인 경로명 조작

Source code: Lib/posixpath.py (for POSIX) and Lib/ntpath.py (for Windows).


This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module. The path parameters can be passed as strings, or bytes, or any object implementing the os.PathLike protocol.

Unlike a Unix shell, Python does not do any automatic path expansions. Functions such as expanduser() and expandvars() can be invoked explicitly when an application desires shell-like path expansion. (See also the glob module.)

더 보기

pathlib 모듈은 고수준의 경로 객체를 제공합니다.

참고

이 모든 함수는 매개 변수가 모두 바이트열 객체이거나 모두 문자열 객체인 것만 허락합니다. 경로나 파일 이름이 반환되면, 결과는 같은 형의 객체입니다.

참고

운영 체제마다 경로 이름 규칙이 다르기 때문에, 표준 라이브러리에 이 모듈의 여러 버전이 있습니다. os.path 모듈은 항상 파이썬이 실행 중인 운영 체제에 적합한 경로 모듈이고, 따라서 지역 경로에 사용할 수 있습니다. 그러나, 항상 다른 형식 중 하나인 경로를 조작하려면 개별 모듈을 임포트 해서 사용할 수도 있습니다. 그들은 모두 같은 인터페이스를 가지고 있습니다:

  • 유닉스 스타일 경로는 posixpath

  • 윈도우 경로는 ntpath

버전 3.8에서 변경: exists(), lexists(), isdir(), isfile(), islink()ismount()는 이제 OS 수준에서 표현할 수 없는 문자나 바이트를 포함하는 경로에 대해 예외를 발생시키는 대신 False를 반환합니다.

os.path.abspath(path)

경로명 path의 정규화된 절대 버전을 반환합니다. 대부분의 플랫폼에서, 이는 다음과 같이 normpath() 함수를 호출하는 것과 동등합니다: normpath(join(os.getcwd(), path)).

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.basename(path)

경로명 path의 기본 이름을 반환합니다. 이것은 path를 함수 split()에 전달하여 반환된 쌍의 두 번째 요소입니다. 이 함수의 결과는 유닉스 basename 프로그램과 다름에 유의하십시오; '/foo/bar/'에 대해 basename'bar'를 반환하고, basename() 함수는 빈 문자열('')을 반환합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.commonpath(paths)

시퀀스 paths에 있는 각 경로명의 가장 긴 공통 하위 경로(sub-path)를 반환합니다. paths에 절대 경로명과 상대 경로명이 모두 있거나 paths가 다른 드라이브에 있거나 paths가 비어 있으면 ValueError를 발생시킵니다. commonprefix()와 달리, 유효한 경로를 반환합니다.

가용성: 유닉스, 윈도우

버전 3.5에 추가.

버전 3.6에서 변경: 경로류 객체의 시퀀스를 받아들입니다.

os.path.commonprefix(list)

list에 있는 모든 경로의 접두사인 가장 긴 경로 접두사(문자 단위로 취합니다)를 반환합니다. list가 비어 있으면, 빈 문자열('')을 반환합니다.

참고

이 함수는 한 번에 한 문자씩 다루기 때문에 유효하지 않은 경로를 반환할 수 있습니다. 유효한 경로를 얻으려면, commonpath()를 참조하십시오.

>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.dirname(path)

경로명 path의 디렉터리 이름을 반환합니다. 이것은 path를 함수 split()에 전달하여 반환된 쌍의 첫 번째 요소입니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.exists(path)

path가 기존 경로나 열린 파일 기술자를 참조하면 True를 반환합니다. 깨진 심볼릭 링크에 대해서는 False를 반환합니다. 일부 플랫폼에서, path가 물리적으로 존재하더라도, 요청된 파일에 대해 os.stat()을 실행할 권한이 없으면 이 함수는 False를 반환할 수 있습니다.

버전 3.3에서 변경: path는 이제 정수가 될 수 있습니다: 열린 파일 기술자이면 True가 반환되고, 그렇지 않으면 False가 반환됩니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.lexists(path)

path가 기존 경로를 참조하면 True를 반환합니다. 깨진 심볼릭 링크에 대해 True를 반환합니다. os.lstat()이 없는 플랫폼에서 exists()와 동등합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.expanduser(path)

유닉스와 윈도우에서, ~~user의 초기 구성 요소가 해당 사용자의 홈 디렉터리로 치환된 인자를 반환합니다.

유닉스에서, 초기 ~는 환경 변수 HOME이 설정되어 있다면 그것으로 치환됩니다; 그렇지 않으면 현재 사용자의 홈 디렉터리가 내장 모듈 pwd를 통해 비밀번호 디렉터리에서 조회됩니다. 초기 ~user는 비밀번호 디렉터리에서 직접 조회됩니다.

On Windows, USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by checking that the last directory component of the current user’s home directory matches USERNAME, and replacing it if so.

확장이 실패하거나 경로가 물결표로 시작하지 않으면, 경로는 변경되지 않은 상태로 반환됩니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.8에서 변경: 더는 윈도우에서 HOME을 사용하지 않습니다.

os.path.expandvars(path)

환경 변수로 확장된 인자를 반환합니다. $name이나 ${name} 형식의 부분 문자열이 환경 변수 name의 값으로 치환됩니다. 잘못된 변수 이름과 존재하지 않는 변수에 대한 참조는 변경되지 않고 남습니다.

윈도우에서, $name${name} 외에 %name% 확장이 지원됩니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.getatime(path)

path의 마지막 액세스 시간을 반환합니다. 반환 값은 에포크(epoch) 이후 초 수를 나타내는 부동 소수점 숫자입니다 (time 모듈을 참조하십시오). 파일이 없거나 액세스할 수 없으면 OSError를 발생시킵니다.

os.path.getmtime(path)

path를 마지막으로 수정한 시간을 반환합니다. 반환 값은 에포크(epoch) 이후 초 수를 나타내는 부동 소수점 숫자입니다 (time 모듈을 참조하십시오). 파일이 없거나 액세스할 수 없으면 OSError를 발생시킵니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.getctime(path)

시스템의 ctime을 반환하는데, 일부 시스템(가령 유닉스)에서는 마지막 메타 데이터 변경 시간이고, 다른 시스템(가령 윈도우)에서는 path 생성 시간입니다. 반환 값은 에포크(epoch) 이후 초 수를 나타내는 부동 소수점 숫자입니다 (time 모듈을 참조하십시오). 파일이 없거나 액세스할 수 없으면 OSError를 발생시킵니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.getsize(path)

path의 크기를 바이트 단위로 반환합니다. 파일이 없거나 액세스할 수 없으면 OSError를 발생시킵니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.isabs(path)

path가 절대 경로명이면 True를 반환합니다. 유닉스에서는 슬래시로 시작하고, 윈도우에서는 잠재적 드라이브 문자를 잘라낸 후 (역) 슬래시로 시작함을 의미합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.isfile(path)

path존재하는 일반 파일이면 True를 반환합니다. 이것은 심볼릭 링크를 따르므로, 같은 경로에 대해 islink()isfile()이 모두 참일 수 있습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.isdir(path)

path존재하는 디렉터리이면 True를 반환합니다. 이것은 심볼릭 링크를 따르므로, 같은 경로에 대해 islink()isdir()이 모두 참일 수 있습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.isjunction(path)

Return True if path refers to an existing directory entry that is a junction. Always return False if junctions are not supported on the current platform.

버전 3.12에 추가.

path가 심볼릭 링크인 존재하는 디렉터리 항목을 가리키면 True를 반환합니다. 파이썬 런타임에서 심볼릭 링크를 지원하지 않으면 항상 False입니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.ismount(path)

경로명 path마운트 지점(mount point)이면 True를 반환합니다: 다른 파일 시스템이 마운트된 파일 시스템의 지점. POSIX에서, 이 함수는 path의 부모 path/..path와 다른 장치에 있는지, 또는 path/..path가 같은 장치에서 같은 i-노드를 가리키는지를 확인합니다 — 이 방법은 모든 유닉스와 POSIX 변형에서 마운트 지점을 감지해야 합니다. 같은 파일 시스템에서의 바인드 마운트(bind mounts)를 신뢰성 있게 감지할 수 없습니다. 윈도우에서, 드라이브 문자 루트와 공유 UNC는 항상 마운트 지점이며, 다른 경로의 경우 GetVolumePathName을 호출해서 입력 경로와 다른지 봅니다.

버전 3.4에 추가: 윈도우에서 비 루트 마운트 지점 감지 지원.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.isdevdrive(path)

Return True if pathname path is located on a Windows Dev Drive. A Dev Drive is optimized for developer scenarios, and offers faster performance for reading and writing files. It is recommended for use for source code, temporary build directories, package caches, and other IO-intensive operations.

May raise an error for an invalid path, for example, one without a recognizable drive, but returns False on platforms that do not support Dev Drives. See the Windows documentation for information on enabling and creating Dev Drives.

Availability: Windows.

버전 3.12에 추가.

os.path.join(path, *paths)

Join one or more path segments intelligently. The return value is the concatenation of path and all members of *paths, with exactly one directory separator following each non-empty part, except the last. That is, the result will only end in a separator if the last part is either empty or ends in a separator. If a segment is an absolute path (which on Windows requires both a drive and a root), then all previous segments are ignored and joining continues from the absolute path segment.

On Windows, the drive is not reset when a rooted path segment (e.g., r'\foo') is encountered. If a segment is on a different drive or is an absolute path, all previous segments are ignored and the drive is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

버전 3.6에서 변경: pathpaths에 대해 경로류 객체를 받아들입니다.

os.path.normcase(path)

경로명의 대소 문자를 정규화합니다. 윈도우에서는, 경로명의 모든 문자를 소문자로 변환하고, 슬래시도 역 슬래시로 변환합니다. 다른 운영 체제에서는, 경로를 변경하지 않고 반환합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.normpath(path)

중복된 구분자와 상위 수준 참조를 접어 경로명을 정규화합니다. 그래서 A//B, A/B/, A/./BA/foo/../B가 모두 A/B가 됩니다. 이 문자열 조작은 심볼릭 링크가 포함된 경로의 의미를 변경할 수 있습니다. 윈도우에서는, 슬래시를 역 슬래시로 변환합니다. 대소 문자를 정규화하려면, normcase()를 사용하십시오.

참고

On POSIX systems, in accordance with IEEE Std 1003.1 2013 Edition; 4.13 Pathname Resolution, if a pathname begins with exactly two slashes, the first component following the leading characters may be interpreted in an implementation-defined manner, although more than two leading characters shall be treated as a single character.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.realpath(path, *, strict=False)

(운영 체제에서 지원한다면) 경로에서 발견된 심볼릭 링크를 제거해서 지정된 파일명의 규범적(canonical) 경로를 반환합니다.

If a path doesn’t exist or a symlink loop is encountered, and strict is True, OSError is raised. If strict is False, the path is resolved as far as possible and any remainder is appended without checking whether it exists.

참고

This function emulates the operating system’s procedure for making a path canonical, which differs slightly between Windows and UNIX with respect to how links and subsequent path components interact.

Operating system APIs make paths canonical as needed, so it’s not normally necessary to call this function.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.8에서 변경: 윈도우에서 심볼릭 링크와 정션(junctions)이 이제 해석됩니다.

버전 3.10에서 변경: The strict parameter was added.

os.path.relpath(path, start=os.curdir)

Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start. On Windows, ValueError is raised when path and start are on different drives.

start defaults to os.curdir.

가용성: 유닉스, 윈도우

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.samefile(path1, path2)

두 경로명 인자가 같은 파일이나 디렉터리를 가리키면 True를 반환합니다. 장치 번호와 i-노드 번호로 결정하며 경로명 중 어느 하나에 대해 os.stat() 호출이 실패하면 예외를 발생시킵니다.

가용성: 유닉스, 윈도우

버전 3.2에서 변경: 윈도우 지원이 추가되었습니다.

버전 3.4에서 변경: 윈도우는 이제 다른 모든 플랫폼과 같은 구현을 사용합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.sameopenfile(fp1, fp2)

파일 기술자 fp1fp2가 같은 파일을 가리키면 True를 반환합니다.

가용성: 유닉스, 윈도우

버전 3.2에서 변경: 윈도우 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.samestat(stat1, stat2)

stat 튜플 stat1stat2가 같은 파일을 가리키면 True를 반환합니다. 이러한 구조는 os.fstat(), os.lstat() 또는 os.stat()에 의해 반환되었을 수 있습니다. 이 함수는 samefile()sameopenfile()에서 사용하는 하부 비교를 구현합니다.

가용성: 유닉스, 윈도우

버전 3.4에서 변경: 윈도우 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.split(path)

path 경로명을 (head, tail) 쌍으로 분할합니다. 여기서 tail은 마지막 경로명 구성 요소이고 head는 그 앞에 오는 모든 것입니다. tail 부분에는 슬래시가 포함되지 않습니다; path가 슬래시로 끝나면, tail은 비어 있습니다. path에 슬래시가 없으면, head는 비어 있습니다. path가 비어 있으면, headtail이 모두 비어 있습니다. 후행 슬래시는 루트(하나나 그 이상의 슬래시로만 구성됩니다)가 아니라면 head에서 제거됩니다. 모든 경우에, join(head, tail)path와 같은 위치에 대한 경로를 반환합니다 (하지만 문자열은 다를 수 있습니다). dirname()basename() 함수도 참조하십시오.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.splitdrive(path)

경로명 path를 쌍 (drive, tail)로 분할합니다. 여기서 drive는 마운트 지점이나 빈 문자열입니다. 드라이브 지정을 사용하지 않는 시스템에서 drive는 항상 빈 문자열입니다. 모든 경우에, drive + tailpath와 같습니다.

윈도우에서는, 경로명을 드라이브/UNC 공유 지점과 상대 경로로 분할합니다.

If the path contains a drive letter, drive will contain everything up to and including the colon:

>>> splitdrive("c:/dir")
("c:", "/dir")

If the path contains a UNC path, drive will contain the host name and share:

>>> splitdrive("//host/computer/dir")
("//host/computer", "/dir")

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.splitroot(path)

Split the pathname path into a 3-item tuple (drive, root, tail) where drive is a device name or mount point, root is a string of separators after the drive, and tail is everything after the root. Any of these items may be the empty string. In all cases, drive + root + tail will be the same as path.

On POSIX systems, drive is always empty. The root may be empty (if path is relative), a single forward slash (if path is absolute), or two forward slashes (implementation-defined per IEEE Std 1003.1-2017; 4.13 Pathname Resolution.) For example:

>>> splitroot('/home/sam')
('', '/', 'home/sam')
>>> splitroot('//home/sam')
('', '//', 'home/sam')
>>> splitroot('///home/sam')
('', '/', '//home/sam')

On Windows, drive may be empty, a drive-letter name, a UNC share, or a device name. The root may be empty, a forward slash, or a backward slash. For example:

>>> splitroot('C:/Users/Sam')
('C:', '/', 'Users/Sam')
>>> splitroot('//Server/Share/Users/Sam')
('//Server/Share', '/', 'Users/Sam')

버전 3.12에 추가.

os.path.splitext(path)

Split the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is empty or begins with a period and contains at most one period.

If the path contains no extension, ext will be '':

>>> splitext('bar')
('bar', '')

If the path contains an extension, then ext will be set to this extension, including the leading period. Note that previous periods will be ignored:

>>> splitext('foo.bar.exe')
('foo.bar', '.exe')
>>> splitext('/foo/bar.exe')
('/foo/bar', '.exe')

Leading periods of the last component of the path are considered to be part of the root:

>>> splitext('.cshrc')
('.cshrc', '')
>>> splitext('/foo/....jpg')
('/foo/....jpg', '')

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.path.supports_unicode_filenames

(파일 시스템에 의해 부과된 제한 내에서) 임의의 유니코드 문자열을 파일 이름으로 사용할 수 있으면 True.