Python

pathlib — 객체 지향 파일 시스템 경로

Added in version 3.4.

소스 코드: Lib/pathlib/


이 모듈은 다른 운영 체제에 적합한 의미 체계를 가진 파일 시스템 경로를 나타내는 클래스를 제공합니다. 경로 클래스는 I/O 없이 순수한 계산 연산을 제공하는 순수한 경로와 순수한 경로를 상속하지만, I/O 연산도 제공하는 구상 경로로 구분됩니다.

Inheritance diagram showing the classes available in pathlib. The most basic class is PurePath, which has three direct subclasses: PurePosixPath, PureWindowsPath, and Path. Further to these four classes, there are two classes that use multiple inheritance: PosixPath subclasses PurePosixPath and Path, and WindowsPath subclasses PureWindowsPath and Path.

이전에 이 모듈을 사용한 적이 없거나 어떤 클래스가 작업에 적합한지 확신이 없다면, Path가 가장 적합할 가능성이 높습니다. 코드가 실행되는 플랫폼의 구상 경로를 인스턴스화 합니다.

순수한 경로는 특별한 경우에 유용합니다; 예를 들면:

  1. 유닉스 기계에서 윈도우 경로를 조작하려고 할 때 (또는 그 반대). 유닉스에서 실행할 때는 WindowsPath를 인스턴스화 할 수 없지만, PureWindowsPath는 인스턴스화 할 수 있습니다.

  2. 코드가 실제로 OS에 액세스하지 않고 경로만 조작한다는 확신이 필요할 때. 이 경우, 순수 클래스 중 하나를 인스턴스화 하면 OS 액세스 연산이 없어서 유용 할 수 있습니다.

더 보기

PEP 428: pathlib 모듈 – 객체 지향 파일 시스템 경로.

더 보기

문자열에 대한 저수준 경로 조작을 위해, os.path 모듈을 사용할 수도 있습니다.

기본 사용

메인 클래스 임포트 하기:

>>> from pathlib import Path

서브 디렉터리 나열하기:

>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]

이 디렉터리 트리에 있는 파이썬 소스 파일 나열하기:

>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]

디렉터리 트리 내에서 탐색하기:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

경로 속성 조회하기:

>>> q.exists()
True
>>> q.is_dir()
False

파일 열기:

>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'

예외 처리

exception pathlib.UnsupportedOperation

An exception inheriting NotImplementedError that is raised when an unsupported operation is called on a path object.

Added in version 3.13.

순수한 경로

순수한 경로 객체는 실제로 파일 시스템에 액세스하지 않는 경로 처리 연산을 제공합니다. 이 클래스에 액세스하는 방법에는 세 가지가 있으며, 플레이버(flavours)라고도 부릅니다:

class pathlib.PurePath(*pathsegments)

시스템의 경로 플레이버를 나타내는 일반 클래스 (인스턴스화 하면 PurePosixPathPureWindowsPath를 만듭니다):

>>> PurePath('setup.py')      # Unix 시스템에서 실행
PurePosixPath('setup.py')

pathsegments 의 각 요소는 경로 세그먼트를 나타내는 문자열일 수도 있고, __fspath__() 메서드가 다른 경로 객체와 같은 문자열을 반환하는 os.PathLike 인터페이스를 구현하는 객체일 수도 있습니다:

>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')

pathsegments가 비어 있으면, 현재 디렉터리를 가정합니다:

>>> PurePath()
PurePosixPath('.')

If a segment is an absolute path, all previous segments are ignored (like os.path.join()):

>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')

윈도우에서 루트 상대 경로 세그먼트(예: r'\foo')에 도달했을 때 드라이브가 재설정되지 않습니다.

>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')

가짜 슬래시와 단일 점은 축소되지만, 이중 점 ('..')과 선행 이중 슬래시는 축소되지 않습니다. 이는 다양한 이유(예: 심볼릭 링크, UNC 경로)로 인해 경로의 의미를 변경할 수 있기 때문입니다:

>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> PurePath('//foo/bar')
PurePosixPath('//foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('foo/../bar')

(나이브한 접근법은 PurePosixPath('foo/../bar')PurePosixPath('bar')와 동등하게 만드는데, foo가 다른 디렉터리에 대한 심볼릭 링크일 때는 잘못됩니다)

순수한 경로 객체는 os.PathLike 인터페이스를 구현하여, 이 인터페이스가 허용되는 모든 위치에서 사용할 수 있습니다.

버전 3.6에서 변경: os.PathLike 인터페이스에 대한 지원이 추가되었습니다.

class pathlib.PurePosixPath(*pathsegments)

PurePath의 서브 클래스, 이 경로 플레이버는 윈도우 이외의 파일 시스템 경로를 나타냅니다:

>>> PurePosixPath('/etc/hosts')
PurePosixPath('/etc/hosts')

pathsegmentsPurePath와 유사하게 지정됩니다.

class pathlib.PureWindowsPath(*pathsegments)

PurePath 의 서브 클래스이며, 이 경로 플레이버는 UNC paths 를 포함하여 Windows 파일 시스템 경로를 나타냅니다:

>>> PureWindowsPath('c:/', 'Users', 'Ximénez')
PureWindowsPath('c:/Users/Ximénez')
>>> PureWindowsPath('//server/share/file')
PureWindowsPath('//server/share/file')

pathsegmentsPurePath와 유사하게 지정됩니다.

실행 중인 시스템과 관계없이, 이러한 모든 클래스를 인스턴스화 할 수 있는데, 시스템 호출을 수행하는 연산을 제공하지 않기 때문입니다.

일반 속성

경로(Paths)는 불변하며 hashable 합니다. 동일한 플레이버의 경로들은 비교 가능하고 순서 지정이 가능합니다. 이러한 속성들은 해당 플레이버의 케이스 폴딩 의미론을 준수합니다:

>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True

다른 플레이버의 경로는 다르다고 비교되며 대소 비교할 수 없습니다:

>>> PureWindowsPath('foo') == PurePosixPath('foo')
False
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'

연산자

슬래시 연산자는 os.path.join`처럼 하위 경로를 생성하는 도움을 줍니다. 인자가 절대 경로인 경우 이전 경로는 무시됩니다. Windows에서는 인자가 루트 상대 경로인 경우(예: ``r'foo'`()) 드라이브가 재설정되지 않습니다:

>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')
>>> p / '/an_absolute_path'
PurePosixPath('/an_absolute_path')
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')

경로 객체는 os.PathLike을 구현하는 객체가 허용되는 모든 곳에서 사용할 수 있습니다:

>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'

경로의 문자열 표현은 원시 파일 시스템 경로 자체(네이티브 형식으로, 예를 들어 윈도우에서 역 슬래시)로, 파일 경로를 문자열로 받아들이는 모든 함수에 전달할 수 있습니다:

>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'

마찬가지로, 경로에 대해 bytes를 호출하면 os.fsencode()로 인코딩된 바이트열 객체로 원시 파일 시스템 경로를 제공합니다:

>>> bytes(p)
b'/etc'

참고

bytes 호출은 유닉스에서만 권장됩니다. 윈도우에서, 유니코드 형식이 파일 시스템 경로의 규범적(canonical) 표현입니다.

개별 부분에 액세스하기

경로의 개별 “부분”(구성 요소)에 액세스하려면, 다음 프로퍼티를 사용하십시오:

PurePath.parts

경로의 다양한 구성 요소로의 액세스를 제공하는 튜플:

>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')

(드라이브와 로컬 루트가 단일 부분으로 다시 그룹화되는 방식에 유의하십시오)

메서드와 프로퍼티

순수한 경로는 다음과 같은 메서드와 프로퍼티를 제공합니다:

PurePath.parser

저수준 경로 파싱 및 결합에 사용되는 os.path 모듈의 구현체입니다: posixpath 또는 ntpath.

Added in version 3.13.

PurePath.drive

드라이브 문자나 이름을 나타내는 문자열, 있다면:

>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
''
>>> PurePosixPath('/etc').drive
''

UNC 공유도 드라이브로 간주합니다:

>>> PureWindowsPath('//host/share/foo.txt').drive
'\\\\host\\share'
PurePath.root

(로컬이나 글로벌) 루트를 나타내는 문자열, 있다면:

>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
''
>>> PurePosixPath('/etc').root
'/'

UNC 공유에는 항상 루트가 있습니다:

>>> PureWindowsPath('//host/share').root
'\\'

If the path starts with more than two successive slashes, PurePosixPath collapses them:

>>> PurePosixPath('//etc').root
'//'
>>> PurePosixPath('///etc').root
'/'
>>> PurePosixPath('////etc').root
'/'

참고

이 동작은 The Open Group Base Specifications Issue 6 의 문단 4.11 Pathname Resolution <https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11>: 에 따릅니다.

“두 개의 연속된 슬래시로 시작하는 경로명은 구현 정의 방식으로 해석될 수 있지만, 두 개 이상의 선행 슬래시는 단일 슬래시로 처리되어야 합니다.”

PurePath.anchor

드라이브와 루트의 이어 붙이기:

>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
>>> PureWindowsPath('//host/share').anchor
'\\\\host\\share\\'
PurePath.parents

경로의 논리적 조상에 대한 액세스를 제공하는 불변 시퀀스:

>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')

버전 3.10에서 변경: The parents sequence now supports slices and negative index values.

PurePath.parent

경로의 논리적 부모:

>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')

앵커나 빈 경로를 넘어갈 수 없습니다:

>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')

참고

이것은 순수한 어휘(lexical) 연산이라서, 다음과 같이 동작합니다:

>>> p = PurePosixPath('foo/..')
>>> p.parent
PurePosixPath('foo')

If you want to walk an arbitrary filesystem path upwards, it is recommended to first call Path.resolve() so as to resolve symlinks and eliminate ".." components.

PurePath.name

드라이브와 루트를 제외하고, 마지막 경로 구성 요소를 나타내는 문자열, 있다면:

>>> PurePosixPath('my/library/setup.py').name
'setup.py'

UNC 드라이브 이름은 고려되지 않습니다:

>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''
PurePath.suffix

최종 구성 요소의 마지막 점으로 구분된 부분입니다:

>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''

이것은 일반적으로 파일 확장이라고 불립니다.

버전 3.14에서 변경: A single dot (”.”) is considered a valid suffix.

PurePath.suffixes

경로의 접미사 목록, 파일 확장자라고도 함:

>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]

버전 3.14에서 변경: A single dot (”.”) is considered a valid suffix.

PurePath.stem

suffix가 없는, 마지막 경로 구성 요소:

>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'

버전 3.14에서 변경: A single dot (”.”) is considered a valid suffix.

PurePath.as_posix()

슬래시(/)가 있는 경로의 문자열 표현을 반환합니다:

>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
PurePath.is_absolute()

경로가 절대적인지 아닌지를 반환합니다. 루트와 (플레이버가 허락하면) 드라이브가 모두 있으면 경로를 절대적이라고 간주합니다:

>>> PurePosixPath('/a/b').is_absolute()
True
>>> PurePosixPath('a/b').is_absolute()
False

>>> PureWindowsPath('c:/a/b').is_absolute()
True
>>> PureWindowsPath('/a/b').is_absolute()
False
>>> PureWindowsPath('c:').is_absolute()
False
>>> PureWindowsPath('//some/share').is_absolute()
True
PurePath.is_relative_to(other)

이 경로가 other 경로에 상대적인지를 반환합니다.

>>> p = PurePath('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
False

이 방법은 문자열 기반이며, 파일 시스템에 접근하거나 “..” 세그먼트를 특별하게 취급하지 않습니다. 다음 코드는 이에 상응합니다:

>>> u = PurePath('/usr')
>>> u == p or u in p.parents
False

Added in version 3.9.

버전 3.12부터 사용 지원 중단(deprecated), 버전 3.14에서 제거됨: 추가 인자를 전달하는 것은 사용 중단되었습니다; 제공된 경우, other 와 결합됩니다.

PurePath.joinpath(*pathsegments)

이 메서드를 호출하는 것은 경로를 주어진 pathsegments 각각과 순차적으로 결합하는 것과 동일합니다:

>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')
PurePath.full_match(pattern, *, case_sensitive=None)

제공된 glob 스타일 패턴과 이 경로를 일치시킵니다. 매칭에 성공하면 True 를, 그렇지 않으면 False 를 반환합니다. 예시:

>>> PurePath('a/b.py').full_match('a/*.py')
True
>>> PurePath('a/b.py').full_match('*.py')
False
>>> PurePath('/a/b/c.py').full_match('/a/**')
True
>>> PurePath('/a/b/c.py').full_match('**/*.py')
True

더 보기

패턴 언어 문서.

다른 메서드와 마찬가지로, 대소 문자를 구분할지는 플랫폼 기본값을 따릅니다:

>>> PurePosixPath('b.py').full_match('*.PY')
False
>>> PureWindowsPath('b.py').full_match('*.PY')
True

이 동작을 재정의하려면 case_sensitiveTrue 또는 False 로 설정하십시오.

Added in version 3.13.

PurePath.match(pattern, *, case_sensitive=None)

이 경로를 제공된 비재귀 glob 스타일 패턴과 일치시킵니다. 일치하는 경우 True 를, 그렇지 않은 경우 False 를 반환합니다.

This method is similar to full_match(), but empty patterns aren’t allowed (ValueError is raised), the recursive wildcard “**” isn’t supported (it acts like non-recursive “*”), and if a relative pattern is provided, then matching is done from the right:

>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False

버전 3.12에서 변경: The pattern parameter accepts a path-like object.

버전 3.12에서 변경: *case_sensitive* 매개 변수가 추가되었습니다.

PurePath.relative_to(other, walk_up=False)

이 경로를 other 가 나타내는 경로와 상대적인 버전으로 계산하십시오. 불가능한 경우, ValueError 가 발생합니다:

>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 941, in relative_to
    raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other is absolute.

walk_up 이 거짓(기본값)인 경우, 경로는 other 로 시작해야 합니다. 이 인수가 참일 경우, .. 항목들이 상대 경로를 형성하는 데 추가될 수 있습니다. 그 외의 모든 경우, 예를 들어 드라이브가 다른 경로의 경우, ValueError 가 발생합니다:

>>> p.relative_to('/usr', walk_up=True)
PurePosixPath('../etc/passwd')
>>> p.relative_to('foo', walk_up=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 941, in relative_to
    raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not on the same drive as 'foo' OR one path is relative and the other is absolute.

경고

This function is part of PurePath and works with strings. It does not check or access the underlying file structure. This can impact the walk_up option as it assumes that no symlinks are present in the path; call resolve() first if necessary to resolve symlinks.

버전 3.12에서 변경: walk_up 매개변수가 추가되었습니다 (기존 동작은 walk_up=False 와 동일합니다).

버전 3.12부터 사용 지원 중단(deprecated), 버전 3.14에서 제거됨: 추가 위치 인자를 전달하는 것은 이제 사용이 권장되지 않습니다. 만약 제공되면 other 와 결합됩니다.

PurePath.with_name(name)

name이 변경된 새 경로를 반환합니다. 원래 경로에 이름(name)이 없으면 ValueError가 발생합니다:

>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
>>> p = PureWindowsPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
PurePath.with_stem(stem)

stem이 변경된 새 경로를 반환합니다. 원래 경로에 이름(name)이 없으면, ValueError가 발생합니다:

>>> p = PureWindowsPath('c:/Downloads/draft.txt')
>>> p.with_stem('final')
PureWindowsPath('c:/Downloads/final.txt')
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_stem('lib')
PureWindowsPath('c:/Downloads/lib.gz')
>>> p = PureWindowsPath('c:/')
>>> p.with_stem('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
    return self.with_name(stem + self.suffix)
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name

Added in version 3.9.

PurePath.with_suffix(suffix)

suffix가 변경된 새 경로를 반환합니다. 원래 경로에 접미사(suffix)가 없으면, 새 suffix가 대신 추가됩니다. suffix가 빈 문자열이면, 원래 접미사가 제거됩니다:

>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
>>> p = PureWindowsPath('README.txt')
>>> p.with_suffix('')
PureWindowsPath('README')

버전 3.14에서 변경: A single dot (”.”) is considered a valid suffix. In previous versions, ValueError is raised if a single dot is supplied.

PurePath.with_segments(*pathsegments)

주어진 pathsegments 를 결합하여 같은 유형의 새 경로 객체를 생성합니다. 이 메서드는 parentrelative_to() 처럼 파생되는 경로가 생성될 때마다 호출됩니다. 서브클래스는 예를 들어 파생 경로에 정보를 전달하기 위해 이 메서드를 오버라이드할 수 있습니다:

from pathlib import PurePosixPath

class MyPath(PurePosixPath):
    def __init__(self, *pathsegments, session_id):
        super().__init__(*pathsegments)
        self.session_id = session_id

    def with_segments(self, *pathsegments):
        return type(self)(*pathsegments, session_id=self.session_id)

etc = MyPath('/etc', session_id=42)
hosts = etc / 'hosts'
print(hosts.session_id)  # 42

Added in version 3.12.

구상 경로

구상 경로는 순수한 경로 클래스의 서브 클래스입니다. 후자가 제공하는 연산 외에도, 경로 객체에 대해 시스템 호출을 수행하는 메서드도 제공합니다. 구상 경로를 인스턴스화 하는 세 가지 방법이 있습니다:

class pathlib.Path(*pathsegments)

PurePath의 서브 클래스, 이 클래스는 시스템의 경로 플레이버의 구상 경로를 나타냅니다 (인스턴스화 하면 PosixPathWindowsPath를 만듭니다):

>>> Path('setup.py')
PosixPath('setup.py')

pathsegmentsPurePath와 유사하게 지정됩니다.

class pathlib.PosixPath(*pathsegments)

PathPurePosixPath의 서브 클래스, 이 클래스는 윈도우 이외의 구상 파일 시스템 경로를 나타냅니다:

>>> PosixPath('/etc/hosts')
PosixPath('/etc/hosts')

pathsegmentsPurePath와 유사하게 지정됩니다.

버전 3.13에서 변경: Raises UnsupportedOperation on Windows. In previous versions, NotImplementedError was raised instead.

class pathlib.WindowsPath(*pathsegments)

PathPureWindowsPath의 서브 클래스, 이 클래스는 구상 윈도우 파일 시스템 경로를 나타냅니다:

>>> WindowsPath('c:/', 'Users', 'Ximénez')
WindowsPath('c:/Users/Ximénez')

pathsegmentsPurePath와 유사하게 지정됩니다.

버전 3.13에서 변경: Raises UnsupportedOperation on non-Windows platforms. In previous versions, NotImplementedError was raised instead.

여러분의 시스템에 해당하는 클래스 플레이버만 인스턴스화 할 수 있습니다 (호환되지 않는 경로 플레이버에 대한 시스템 호출을 허용하면 응용 프로그램에서 버그나 실패가 발생할 수 있습니다):

>>> import os
>>> os.name
'posix'
>>> Path('setup.py')
PosixPath('setup.py')
>>> PosixPath('setup.py')
PosixPath('setup.py')
>>> WindowsPath('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 798, in __new__
    % (cls.__name__,))
UnsupportedOperation: cannot instantiate 'WindowsPath' on your system

Some concrete path methods can raise an OSError if a system call fails (for example because the path doesn’t exist).

URI 파싱 및 생성

Concrete path objects can be created from, and represented as, ‘file’ URIs conforming to RFC 8089.

참고

File URIs are not portable across machines with different filesystem encodings.

classmethod Path.from_uri(uri)

‘파일’ URI를 구문 분석하여 새로운 경로 객체를 반환합니다. 예를 들면:

>>> p = Path.from_uri('file:///etc/hosts')
PosixPath('/etc/hosts')

윈도우에서는 URI로부터 DOS 장치 및 UNC 경로가 파싱될 수 있습니다:

>>> p = Path.from_uri('file:///c:/windows')
WindowsPath('c:/windows')
>>> p = Path.from_uri('file://server/share')
WindowsPath('//server/share')

여러 가지 변형 형태가 지원됩니다:

>>> p = Path.from_uri('file:////server/share')
WindowsPath('//server/share')
>>> p = Path.from_uri('file://///server/share')
WindowsPath('//server/share')
>>> p = Path.from_uri('file:c:/windows')
WindowsPath('c:/windows')
>>> p = Path.from_uri('file:/c|/windows')
WindowsPath('c:/windows')

ValueError is raised if the URI does not start with file:, or the parsed path isn’t absolute.

Added in version 3.13.

버전 3.14에서 변경: URL 권한(authority)이 로컬 호스트 이름과 일치하면 무시됩니다. 그렇지 않은 경우, 해당 자격 증명이 비어있거나 localhost 가 아니면 윈도우에서는 UNC 경로를 반환하고 (이전과 동일), 다른 플랫폼에서는 ValueError 가 발생합니다.

Path.as_uri()

Represent the path as a ‘file’ URI. ValueError is raised if the path isn’t absolute.

>>> p = PosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = WindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'

버전 3.14부터 사용 지원 중단(deprecated), 버전 3.19에서 제거 예정: Calling this method from PurePath rather than Path is possible but deprecated. The method’s use of os.fsencode() makes it strictly impure.

경로 확장 및 해결

classmethod Path.home()

Return a new path object representing the user’s home directory (as returned by os.path.expanduser() with ~ construct). If the home directory can’t be resolved, RuntimeError is raised.

>>> Path.home()
PosixPath('/home/antoine')

Added in version 3.5.

Path.expanduser()

Return a new path with expanded ~ and ~user constructs, as returned by os.path.expanduser(). If a home directory can’t be resolved, RuntimeError is raised.

>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')

Added in version 3.5.

classmethod Path.cwd()

현재 디렉터리를 나타내는 새 경로 객체를 반환합니다. os.getcwd()가 반환하는 것과 유사합니다:

>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
Path.absolute()

정규화하거나 심볼릭 링크를 해결하지 않고 경로를 절대 경로로 만듭니다. 새로운 경로 객체를 반환합니다:

>>> p = Path('tests')
>>> p
PosixPath('tests')
>>> p.absolute()
PosixPath('/home/antoine/pathlib/tests')
Path.resolve(strict=False)

심볼릭 링크를 결정하여, 경로를 절대적으로 만듭니다. 새로운 경로 객체가 반환됩니다:

>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')

..” 구성 요소도 제거됩니다 (이것이 이렇게 하는 유일한 메서드입니다):

>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')

경로가 존재하지 않거나 심볼릭 링크 루프가 발견되고 strictTrue 인 경우 OSError 가 발생합니다. strictFalse 인 경우, 경로는 가능한 한 멀리까지 해결되며 나머지 부분은 존재 여부를 확인하지 않고 추가됩니다.

버전 3.6에서 변경: strict 매개변수가 추가되었습니다 (3.6 이전 동작은 엄격합니다).

버전 3.13에서 변경: Symlink loops are treated like other errors: OSError is raised in strict mode, and no exception is raised in non-strict mode. In previous versions, RuntimeError is raised no matter the value of strict.

심볼릭 링크가 가리키는 경로를 반환합니다 (os.readlink()가 반환하는 것과 유사합니다):

>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.readlink()
PosixPath('setup.py')

Added in version 3.9.

버전 3.13에서 변경: Raises UnsupportedOperation if os.readlink() is not available. In previous versions, NotImplementedError was raised.

파일 유형 및 상태 질의

버전 3.8에서 변경: exists(), is_dir(), is_file(), is_mount(), is_symlink(), is_block_device(), is_char_device(), is_fifo(), is_socket() now return False instead of raising an exception for paths that contain characters unrepresentable at the OS level.

버전 3.14에서 변경: 위의 메서드들은 이제 운영체제에서 발생하는 어떤 OSError 예외도 발생시키지 않고 False 를 반환합니다. 이전 버전에서는 일부 종류의 OSError 예외가 발생했고, 일부는 억제되었습니다. 새로운 동작은 os.path.exists(), os.path.isdir() 등과 일관적입니다. 예외를 억제하지 않고 파일 상태를 검색하려면 stat() 을 사용하십시오.

Path.stat(*, follow_symlinks=True)

이 메서드는 파일에 대한 정보(예: os.stat())를 포함하는 os.stat_result 객체를 반환합니다. 이 결과는 메서드가 호출될 때마다 조회됩니다.

This method normally follows symlinks; to stat a symlink add the argument follow_symlinks=False, or use lstat().

>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554

버전 3.10에서 변경: follow_symlinks 매개변수가 추가되었습니다.

Path.lstat()

Path.stat()과 비슷하지만, 경로가 심볼릭 링크를 가리키면, 대상이 아닌 심볼릭 링크의 정보를 반환합니다.

Path.exists(*, follow_symlinks=True)

경로가 존재하는 파일이나 디렉터리를 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

이 메서드는 일반적으로 심볼릭 링크를 따릅니다. 심볼릭 링크의 존재 여부를 확인하려면 follow_symlinks=False 인자를 추가하십시오.

>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False

버전 3.12에서 변경: follow_symlinks 매개변수가 추가되었습니다.

Path.is_file(*, follow_symlinks=True)

경로가 일반 파일(regular file)을 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 또는 일반 파일이 아닌 다른 항목을 가리키는 경우에는 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

이 메서드는 일반적으로 심볼릭 링크를 따릅니다. 심볼릭 링크를 제외하려면 follow_symlinks=False 인자를 추가하십시오.

버전 3.13에서 변경: follow_symlinks 매개변수가 추가되었습니다.

Path.is_dir(*, follow_symlinks=True)

경로가 디렉터리를 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 또는 디렉터리가 아닌 다른 항목을 가리키는 경우에는 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

이 메서드는 일반적으로 심볼릭 링크를 따릅니다. 디렉터리로의 심볼릭 링크를 제외하려면 follow_symlinks=False 인자를 추가하십시오.

버전 3.13에서 변경: follow_symlinks 매개변수가 추가되었습니다.

경로가 깨진(broken) 심볼릭 링크라도 심볼릭 링크를 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 또는 심볼릭 링크가 아닌 다른 항목을 가리키는 경우에는 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

Path.is_junction()

경로가 접합점(junction)을 가리키면 True, 그 외의 모든 파일 유형에 대해서는 False 를 반환합니다. 현재는 Windows에서만 접합점을 지원합니다.

Added in version 3.12.

Path.is_mount()

마운트 포인트`라고 하는, 다른 파일 시스템이 마운트된 지점이라면 *path*가 그것을 가리키면 ``True``를 반환합니다. POSIX에서는 함수가 *path*’의 부모인 :file:`path/..``가 *path*와 같은 장치에 있는지, 또는 :file:`path/..``와 *path*가 동일한 i-node를 같은 장치상에서 가리키는지 확인하며 — 이는 모든 유닉스 및 POSIX 변종의 마운트 포인트를 감지해야 합니다. Windows에서는 마운트 포인트는 드라이브 문자의 루트(예: ``c:`), UNC 공유(예: \\server\share) 또는 마운트된 파일 시스템 디렉터리로 간주됩니다.

Added in version 3.7.

버전 3.12에서 변경: Windows 지원이 추가되었습니다.

Path.is_socket()

경로가 Unix 소켓을 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 또는 Unix 소켓이 아닌 다른 항목을 가리키는 경우에는 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

Path.is_fifo()

경로가 FIFO(First-In, First-Out)를 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 또는 FIFO가 아닌 다른 항목을 가리키는 경우에는 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

Path.is_block_device()

경로가 블록 장치(block device)를 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 또는 블록 장치가 아닌 다른 항목을 가리키는 경우에는 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

Path.is_char_device()

경로가 문자 장치(character device)를 가리키면 True 를 반환합니다. 경로가 유효하지 않거나, 접근할 수 없거나, 누락된 경우 또는 문자 장치가 아닌 다른 항목을 가리키는 경우에는 False 가 반환됩니다. 이 두 경우를 구별하려면 Path.stat() 을 사용하십시오.

Path.samefile(other_path)

이 경로가 other_path와 같은 파일을 가리키는지를 반환합니다. other_path는 Path 객체이거나 문자열일 수 있습니다. 의미는 os.path.samefile()os.path.samestat()과 유사합니다.

어떤 이유로 파일에 액세스할 수 없으면 OSError가 발생할 수 있습니다.

>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
True

Added in version 3.5.

Path.info

파일 유형 정보를 쿼리할 수 있는 PathInfo 객체입니다. 이 객체는 결과를 캐싱하는 메서드를 노출하여 파일 유형을 전환할 때 필요한 시스템 호출 수를 줄이는 데 도움이 될 수 있습니다. 예를 들어:

>>> p = Path('src')
>>> if p.info.is_symlink():
...     print('symlink')
... elif p.info.is_dir():
...     print('directory')
... elif p.info.exists():
...     print('something else')
... else:
...     print('not found')
...
directory

If the path was generated from Path.iterdir() then this attribute is initialized with some information about the file type gleaned from scanning the parent directory. Merely accessing Path.info does not perform any filesystem queries.

최신 정보를 가져오려면 이 속성의 메서드보다는 Path.is_dir(), is_file(), 그리고 is_symlink() 을 호출하는 것이 가장 좋습니다. 캐시를 재설정하는 방법은 없으며, 대신 p = Path(p) 와 같이 비어 있는 info 캐시를 가진 새 경로 객체를 생성할 수 있습니다.

Added in version 3.14.

파일 읽기 및 쓰기

Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

내장 open() 함수처럼, 경로가 가리키는 파일을 엽니다:

>>> p = Path('setup.py')
>>> with p.open() as f:
...     f.readline()
...
'#!/usr/bin/env python3\n'
Path.read_text(encoding=None, errors=None, newline=None)

가리키는 파일의 디코딩된 내용을 문자열로 반환합니다:

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

파일이 열린 다음에 닫힙니다. 선택적 매개 변수는 open()과 같은 의미입니다.

Added in version 3.5.

버전 3.13에서 변경: newline 매개변수를 추가했습니다.

Path.read_bytes()

가리키는 파일의 바이너리 내용을 바이트열 객체로 반환합니다:

>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

Added in version 3.5.

Path.write_text(data, encoding=None, errors=None, newline=None)

가리키는 파일을 텍스트 모드로 열고, data를 쓴 다음, 파일을 닫습니다:

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

작성된 문자 수를 반환합니다.

같은 이름의 기존 파일을 덮어씁니다. 선택적 매개 변수는 open()에서와 같은 의미입니다.

Added in version 3.5.

버전 3.10에서 변경: newline 매개변수를 추가했습니다.

Path.write_bytes(data)

가리키는 파일을 바이너리 모드로 열고, data를 쓴 다음, 파일을 닫습니다:

>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

작성된 바이트 수를 반환합니다.

같은 이름의 기존 파일을 덮어씁니다.

Added in version 3.5.

디렉터리 읽기

Path.iterdir()

경로가 디렉터리를 가리킬 때, 디렉터리 내용의 경로 객체를 산출합니다:

>>> p = Path('docs')
>>> for child in p.iterdir(): child
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')

자식 항목들은 임의의 순서로 제공되며, 특수 항목 '.''.. 은 포함되지 않습니다. 이터레이터를 생성한 후 디렉터리에서 파일을 제거하거나 추가하는 경우, 해당 파일에 대한 경로 객체가 포함되는지는 명시되어 있지 않습니다.

If the path is not a directory or otherwise inaccessible, OSError is raised.

Path.glob(pattern, *, case_sensitive=None, recurse_symlinks=False)

이 경로로 표현되는 디렉터리에서, 주어진 상대 pattern을 glob 하여, 일치하는 모든 파일을 (종류와 관계없이) 산출합니다:

>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]
>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

참고

경로는 특별한 순서 없이 반환됩니다. 특정 순서가 필요한 경우 결과를 정렬하십시오.

더 보기

패턴 언어 문서.

기본적으로, 또는 case_sensitive 키워드 전용 인자가 None 으로 설정된 경우, 이 메서드는 플랫폼별 대소문자 규칙을 사용하여 경로와 일치합니다. 일반적으로 POSIX에서는 대소문자를 구분하고 Windows에서는 대소문자를 구분하지 않습니다. 이 동작을 재정의하려면 case_sensitiveTrue 또는 False 로 설정하십시오.

기본적으로, 또는 recurse_symlinks 키워드 전용 인자가 False 로 설정된 경우, 이 메서드는 “** “ 와일드카드를 확장할 때를 제외하고는 심볼릭 링크를 따릅니다. 항상 심볼릭 링크를 따르려면 recurse_symlinksTrue 로 설정하십시오.

참고

Any OSError exceptions raised from scanning the filesystem are suppressed. This includes PermissionError when accessing directories without read permission.

인자 self, pattern으로 감사 이벤트 pathlib.Path.glob을 발생시킵니다.

버전 3.12에서 변경: *case_sensitive* 매개 변수가 추가되었습니다.

버전 3.13에서 변경: recurse_symlinks 매개변수가 추가되었습니다.

버전 3.13에서 변경: The pattern parameter accepts a path-like object.

버전 3.13에서 변경: 파일 시스템 스캔 과정에서 발생하는 모든 OSError 예외는 억제됩니다. 이전 버전에서는 이러한 예외들이 많은 경우에 억제되었지만, 모두 그런 것은 아닙니다.

Path.rglob(pattern, *, case_sensitive=None, recurse_symlinks=False)

주어진 상대 pattern 을 재귀적으로 글롭합니다. 이는 Path.glob() 을 “**/ “를 앞에 붙여 호출하는 것과 같습니다.

참고

경로는 특별한 순서 없이 반환됩니다. 특정 순서가 필요한 경우 결과를 정렬하십시오.

참고

Any OSError exceptions raised from scanning the filesystem are suppressed. This includes PermissionError when accessing directories without read permission.

더 보기

패턴 언어Path.glob() 문서를 참조하십시오.

인자 self, pattern으로 감사 이벤트 pathlib.Path.rglob을 발생시킵니다.

버전 3.12에서 변경: *case_sensitive* 매개 변수가 추가되었습니다.

버전 3.13에서 변경: recurse_symlinks 매개변수가 추가되었습니다.

버전 3.13에서 변경: The pattern parameter accepts a path-like object.

Path.walk(top_down=True, on_error=None, follow_symlinks=False)

트리를 하향식 또는 상향식으로 순회하여 디렉터리 트리의 파일명을 생성합니다.

:self 에 루트가 있는 디렉터리 트리 내의 각 디렉터리에 대해, 이 메서드는 3-튜플 (dirpath, dirnames, filenames) 을 산출합니다 (self를 포함하되 ‘.’, ‘..’은 제외합니다).

dirpath 는 현재 순회 중인 디렉터리에 대한 Path 이며, dirnamesdirpath 내부의 하위 디렉터리 이름('.''..' 제외)에 대한 문자열 리스트이고, filenamesdirpath 내 비(非)디렉터리 파일 이름에 대한 문자열 리스트입니다. dirpath 내 파일이나 디렉터리로의 전체 경로(self로 시작)를 얻으려면 dirpath / name 을 실행하십시오. 목록이 정렬되어 있는지 여부는 파일 시스템에 따라 다릅니다.

선택적 인자 top_down 이 true(기본값)인 경우, 디렉터리에 대한 3-튜플은 해당 하위 디렉터리의 튜플보다 먼저 생성됩니다(디렉터리는 하향식으로 순회합니다). top_down 이 false인 경우, 디렉터리에 대한 3-튜플은 모든 하위 디렉터리의 튜플 다음에 생성됩니다(디렉터리가 상향식으로 순회합니다). top_down 의 값에 상관없이, 디렉터리와 그 하위 디렉터리에 대한 튜플이 순회되기 전에 하위 디렉터리 목록이 검색됩니다.

When top_down is true, the caller can modify the dirnames list in-place (for example, using del or slice assignment), and Path.walk() will only recurse into the subdirectories whose names remain in dirnames. This can be used to prune the search, or to impose a specific order of visiting, or even to inform Path.walk() about directories the caller creates or renames before it resumes Path.walk() again. Modifying dirnames when top_down is false has no effect on the behavior of Path.walk() since the directories in dirnames have already been generated by the time dirnames is yielded to the caller.

기본적으로, os.scandir() 호출에서 발생하는 에러는 무시됩니다. 선택적 인자 on_error 가 지정되면, 이는 호출 가능(callable) 객체여야 합니다; 주어진 하나의 인자, 즉 OSError 인스턴스로 시스템이 호출합니다. 이 호출 가능 객체는 에러를 처리하여 탐색을 계속하거나 예외를 다시 발생시켜 탐색을 중단할 수 있습니다. 파일명은 예외 객체의 filename 어트리뷰트로 확인할 수 있습니다.

기본적으로, Path.walk() 는 심볼릭 링크를 따르지 않고 대신 filenames 리스트에 추가합니다. follow_symlinks 를 true로 설정하면 심볼릭 링크가 해결되어 대상에 맞춰 dirnamesfilenames 에 배치되고, 그 결과로 심볼릭 링크가 가리키는 디렉터리를 방문하게 됩니다 (지원되는 경우).

참고

follow_symlinks 를 true로 설정하면 링크가 자기 자신의 부모 디렉터리를 가리킬 경우 무한 재귀(infinite recursion)에 빠질 수 있으므로 주의하십시오. Path.walk() 는 이미 방문한 디렉터리를 추적하지 않습니다.

참고

Path.walk() 는 탐색하는 디렉터리가 실행 중에 수정되지 않는다고 가정합니다. 예를 들어, dirnames 의 디렉터리가 심볼릭 링크로 대체되었고 follow_symlinks 가 false인 경우에도 Path.walk() 는 여전히 그 안으로 하강하려고 시도할 것입니다. 이러한 동작을 방지하려면 dirnames 에서 적절하게 디렉터리를 제거하십시오.

참고

os.walk() 와 달리, Path.walk()follow_symlinks 가 false인 경우 디렉터리로 연결되는 심볼릭 링크를 filenames 에 나열합니다.

이 예제는 __pycache__ 디렉터리를 무시하면서 각 디렉터리 내 모든 파일이 사용하는 바이트 수를 표시합니다:

from pathlib import Path
for root, dirs, files in Path("cpython/Lib/concurrent").walk(on_error=print):
  print(
      root,
      "consumes",
      sum((root / file).stat().st_size for file in files),
      "bytes in",
      len(files),
      "non-directory files"
  )
  if '__pycache__' in dirs:
        dirs.remove('__pycache__')

This next example is a simple implementation of shutil.rmtree(). Walking the tree bottom-up is essential as rmdir() doesn’t allow deleting a directory before it is empty:

# "top" 디렉터리에서 도달 가능한 모든 것을 삭제합니다.
# 주의:  이것은 위험합니다! 예를 들어, top == Path('/'),
# 사용자의 모든 파일을 삭제할 수 있습니다.
for root, dirs, files in top.walk(top_down=False):
    for name in files:
        (root / name).unlink()
    for name in dirs:
        (root / name).rmdir()

Added in version 3.12.

파일 및 디렉터리 생성하기

Path.touch(mode=0o666, exist_ok=True)

주어진 경로에 파일을 만듭니다. mode 가 제공되면, 이는 프로세스의 umask 값과 결합되어 파일 모드와 접근 플래그를 결정합니다. 파일이 이미 존재하는 경우, exist_ok 가 true이면 함수는 성공하고 (수정 시간을 현재 시간으로 업데이트), 그렇지 않으면 FileExistsError 가 발생합니다.

더 보기

open(), write_text()write_bytes() 메서드는 파일을 생성하는 데 자주 사용됩니다.

Path.mkdir(mode=0o777, parents=False, exist_ok=False, *, parent_mode=None)

주어진 경로에 새 디렉터리를 만듭니다. mode 가 제공되면, 이는 프로세스의 umask 값과 결합되어 파일 모드와 접근 플래그를 결정합니다. 경로가 이미 존재하는 경우, FileExistsError 가 발생합니다.

parents가 참이면, 이 경로의 누락 된 부모를 필요하면 만듭니다; 이것들은 mode를 고려하지 않고 기본 권한으로 만들어집니다 (POSIX mkdir -p 명령을 모방합니다).

parent_modeNone 이 아니면, parents 가 true일 때 새로 생성되는 중간 레벨 디렉터리의 모드로 사용됩니다. mode 와 마찬가지로 프로세스의 umask 값과 결합됩니다. 그렇지 않으면 중간 디렉터리는 기본 권한으로 생성됩니다 (마찬가지로 umask의 적용을 받습니다).

parents가 거짓(기본값)이면, 누락된 부모가 FileNotFoundError를 발생시킵니다.

exist_ok가 거짓(기본값)이면, 대상 디렉터리가 이미 존재하면 FileExistsError가 발생합니다.

exist_ok 가 true이면, 주어진 경로가 파일 시스템에 이미 존재하고 디렉터리가 아닐 경우가 아니라면 FileExistsError 는 발생하지 않습니다 (POSIX mkdir -p 명령어와 동일한 동작).

버전 3.5에서 변경: exist_ok 매개 변수가 추가되었습니다.

Added in version 3.15: parent_mode 매개변수.

이 경로를 target 을 가리키는 심볼릭 링크로 만듭니다.

윈도우에서, 심볼릭 링크는 파일 또는 디렉터리를 나타내며, 대상에 동적으로 변형되지 않습니다. 대상이 존재하면, 해당 심볼릭 링크의 유형은 일치하도록 생성됩니다. 그렇지 않으면, target_is_directory 가 true이면 디렉터리로, 아니면 파일 심볼릭 링크(기본값)로 생성됩니다. 비 윈도우 플랫폼에서는 target_is_directory 가 무시됩니다.

>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
>>> p.stat().st_size
956
>>> p.lstat().st_size
8

참고

인자의 순서(링크, 대상)는 os.symlink()와 반대입니다.

버전 3.13에서 변경: Raises UnsupportedOperation if os.symlink() is not available. In previous versions, NotImplementedError was raised.

이 경로를 target 과 동일한 파일에 대한 하드 링크로 만듭니다.

참고

The order of arguments (link, target) is the reverse of os.link()’s.

Added in version 3.10.

버전 3.13에서 변경: Raises UnsupportedOperation if os.link() is not available. In previous versions, NotImplementedError was raised.

복사, 이동 및 삭제

Path.copy(target, *, follow_symlinks=True, preserve_metadata=False)

주어진 target 에 이 파일 또는 디렉터리 트리를 복사하고, target 을 가리키는 새로운 Path 인스턴스를 반환합니다.

소스가 파일인 경우, 대상은 기존 파일을 대체합니다. 소스가 심볼릭 링크이고 follow_symlinks 가 참(기본값)인 경우, 심볼릭 링크의 대상이 복사됩니다. 그렇지 않은 경우, 목적지에 심볼릭 링크가 다시 생성됩니다.

preserve_metadata 가 거짓인 경우 (기본값), 디렉터리 구조와 파일 데이터만 복사되는 것이 보장됩니다. preserve_metadata 를 true로 설정하면, 지원되는 곳에서 파일 및 디렉터리 권한, 플래그, 마지막 접근 시간과 수정 시간이 복사되도록 보장합니다. 이 인수는 Windows에서 파일을 복사할 때는 영향을 미치지 않습니다 (이 경우 메타데이터는 항상 유지됩니다).

참고

운영 체제와 파일 시스템에서 지원하는 경우, 이 메서드는 데이터 블록이 수정될 때만 복사되는 경량 복사를 수행합니다. 이는 copy-on-write로 알려져 있습니다.

Added in version 3.14.

Path.copy_into(target_dir, *, follow_symlinks=True, preserve_metadata=False)

이 파일 또는 디렉터리 트리를 기존 디렉터리인 target_dir 안으로 복사합니다. 다른 인수는 Path.copy`와 동일하게 처리됩니다. 복사를 가리키는 새로운 :class:()!Path` 인스턴스를 반환합니다.

Added in version 3.14.

Path.rename(target)

이 파일 또는 디렉터리를 주어진 target 으로 이름 변경하고, target 을 가리키는 새로운 Path 인스턴스를 반환합니다. Unix에서는 target 이 존재하고 파일인 경우, 사용자가 권한을 가지고 있으면 조용히 대체됩니다. Windows에서는 target 이 존재하면 FileExistsError 가 발생합니다. target 은 문자열 또는 다른 path 객체일 수 있습니다:

>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'

대상 경로는 절대 경로일 수도 있고 상대 경로일 수도 있습니다. 상대 경로는 Path 객체의 디렉터리가 아닌 현재 작업 디렉터리를 기준으로 해석됩니다.

It is implemented in terms of os.rename() and gives the same guarantees.

버전 3.8에서 변경: 반환값이 추가되어 새로운 Path 인스턴스를 반환합니다.

Path.replace(target)

이 파일 또는 디렉터리를 주어진 target 으로 이름 변경하고, target 을 가리키는 새로운 Path 인스턴스를 반환합니다. 만약 target 이 기존 파일이나 비어 있는 디렉터리를 가리킨다면, 무조건 대체됩니다.

대상 경로는 절대 경로일 수도 있고 상대 경로일 수도 있습니다. 상대 경로는 Path 객체의 디렉터리가 아닌 현재 작업 디렉터리를 기준으로 해석됩니다.

버전 3.8에서 변경: 반환값이 추가되어 새로운 Path 인스턴스를 반환합니다.

Path.move(target)

이 파일 또는 디렉터리 트리를 주어진 target 로 이동하고, target 을 가리키는 새로운 Path 인스턴스를 반환합니다.

target 이 존재하지 않으면 생성됩니다. 이 경로와 target 이 모두 기존 파일인 경우, target이 덮어쓰여집니다. 두 경로가 동일한 파일을 가리키거나 디렉터리를 가리키거나, 또는 target 이 비어 있지 않은 디렉터리인 경우 OSError 이 발생합니다.

If both paths are on the same filesystem, the move is performed with os.replace(). Otherwise, this path is copied (preserving metadata and symlinks) and then deleted.

Added in version 3.14.

Path.move_into(target_dir)

이 파일 또는 디렉터리 트리를 기존 디렉터리인 target_dir 안으로 이동합니다. 이동된 경로를 가리키는 새로운 Path 인스턴스를 반환합니다.

Added in version 3.14.

이 파일이나 심볼릭 링크를 제거합니다. 경로가 디렉터리를 가리키면, Path.rmdir()을 대신 사용하십시오.

missing_ok가 거짓(기본값)이면, 경로가 없을 때 FileNotFoundError가 발생합니다.

missing_ok가 참이면, FileNotFoundError 예외는 무시됩니다 (POSIX rm -f 명령과 같은 동작).

버전 3.8에서 변경: missing_ok 매개 변수가 추가되었습니다.

Path.rmdir()

이 디렉터리를 제거합니다. 디렉터리는 비어 있어야 합니다.

권한 및 소유권

Path.owner(*, follow_symlinks=True)

Return the name of the user owning the file. KeyError is raised if the file’s user identifier (UID) isn’t found in the system database.

이 메서드는 일반적으로 심볼릭 링크를 따릅니다. 심볼릭 링크의 소유자를 얻으려면, 인자로 follow_symlinks=False 를 추가하십시오.

버전 3.13에서 변경: Raises UnsupportedOperation if the pwd module is not available. In earlier versions, NotImplementedError was raised.

버전 3.13에서 변경: follow_symlinks 매개변수가 추가되었습니다.

Path.group(*, follow_symlinks=True)

Return the name of the group owning the file. KeyError is raised if the file’s group identifier (GID) isn’t found in the system database.

이 메서드는 일반적으로 심볼릭 링크를 따릅니다. 심볼릭 링크의 그룹을 얻으려면, 인자로 follow_symlinks=False 를 추가하십시오.

버전 3.13에서 변경: Raises UnsupportedOperation if the grp module is not available. In earlier versions, NotImplementedError was raised.

버전 3.13에서 변경: follow_symlinks 매개변수가 추가되었습니다.

Path.chmod(mode, *, follow_symlinks=True)

Change the file mode and permissions, like os.chmod().

이 메서드는 일반적으로 심볼릭 링크를 따릅니다. 일부 Unix 버전은 심볼릭 링크 자체의 권한 변경을 지원합니다. 이 플랫폼에서는 인자로 follow_symlinks=False 를 추가하거나 lchmod() 를 사용할 수 있습니다.

>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060

버전 3.10에서 변경: follow_symlinks 매개변수가 추가되었습니다.

Path.lchmod(mode)

Path.chmod()와 비슷하지만, 경로가 심볼릭 링크를 가리키면, 대상이 아닌 심볼릭 링크의 모드가 변경됩니다.

패턴 언어

The following wildcards are supported in patterns for full_match(), glob() and rglob():

** (전체 세그먼트)

0개 포함 모든 파일 또는 디렉터리 세그먼트에 일치합니다.

* (전체 세그먼트)

하나의 파일 또는 디렉터리 세그먼트에 일치합니다.

* (부분 세그먼트)

모든 구분 기호가 아닌 문자열을 0개 포함하여 일치합니다.

?

구분 기호가 아닌 문자를 하나 일치합니다.

[seq]

seq 내의 한 문자를 일치합니다. 여기서 seq 는 문자열 시퀀스입니다. 범위 표현식도 지원됩니다. 예를 들어, [a-z] 는 모든 소문자 ASCII 문자와 일치합니다. 여러 범위를 결합할 수 있습니다: [a-zA-Z0-9_] 는 모든 ASCII 문자, 숫자 또는 언더스코어와 일치합니다.

[!seq]

seq 에 포함되지 않은 한 문자를 일치합니다. 여기서 seq 는 위의 규칙을 따릅니다.

리터럴 일치를 위해서는, 메타 문자들을 대괄호 안에 넣어야 합니다. 예를 들어, "[?]"``는 ``"?" 문자와 일치합니다.

**” 와일드카드는 재귀적 globbing을 활성화합니다. 몇 가지 예시는 다음과 같습니다:

패턴

의미

**/*

최소한 하나의 세그먼트를 가진 모든 경로입니다.

**/*.py

assets/”로 끝나는 모든 경로입니다.

assets/**

assets/”로 시작하는 모든 경로입니다.

assets/**/*

assets/”로 시작하지만, 자기 자신인 “assets/”는 제외한 모든 경로입니다.

참고

**” 와일드카드를 사용한 globbing은 트리의 모든 디렉터리를 방문합니다. 대규모 디렉터리 트리는 검색에 오랜 시간이 걸릴 수 있습니다.

버전 3.13에서 변경: **”로 끝나는 패턴을 사용한 globbing은 파일과 디렉터리를 모두 반환합니다. 이전 버전에서는, 디렉터리만 반환했습니다.

Path.glob()rglob() 에서, 패턴 끝에 슬래시를 추가하여 디렉터리만 일치시키도록 할 수 있습니다.

버전 3.11에서 변경: 경로 구성 요소 구분 기호 (sep 또는 altsep) 로 끝나는 패턴을 사용한 globbing은 디렉터리만 반환합니다.

glob 모듈과의 비교

Path.glob()Path.rglob() 이 수락하고 생성하는 패턴은 glob 모듈의 것과 약간 다릅니다:

  1. 점(.)으로 시작하는 파일은 pathlib에서는 특별하지 않습니다. 이는 glob.glob`에 ``include_hidden=True`() 를 전달하는 경우와 같습니다.

  2. **” 패턴 구성 요소는 pathlib에서 항상 재귀적입니다. 이는 glob.glob`에 ``recursive=True`() 를 전달하는 것과 같습니다.

  3. **” pattern components do not follow symlinks by default in pathlib. This behaviour has no equivalent in glob.glob(), but you can pass recurse_symlinks=True to Path.glob() for compatible behaviour.

  4. 모든 PurePathPath 객체와 마찬가지로, Path.glob()Path.rglob() 에서 반환되는 값에는 끝에 슬래시가 포함되지 않습니다.

  5. pathlib의 path.glob()path.rglob() 에서 반환되는 값은, glob.glob(root_dir=path) 의 결과와 달리 path 를 접두사로 포함합니다.

  6. pathlib의 path.glob()path.rglob() 에서 반환되는 값은, 특히 “** “ 을 globbing할 때 path 자체를 포함할 수 있는 반면, glob.glob(root_dir=path) 의 결과는 path 에 해당하는 빈 문자열을 절대 포함하지 않습니다.

osos.path 모듈과의 비교

pathlib은 PurePathPath 객체를 사용하여 경로 작업을 구현하므로 객체 지향적 이라고 합니다. 반면에, osos.path 모듈은 낮은 수준의 strbytes 객체와 작동하는 함수를 제공하며, 이는 보다 절차적 인 접근 방식입니다. 일부 사용자는 객체 지향 스타일이 더 읽기 쉽다고 생각합니다.

osos.path`의 많은 함수는 ``bytes` 경로와 디렉터리 기술자 기준으로 상대적인 <dir_fd> 를 지원합니다. 이 기능들은 pathlib에서는 사용할 수 없습니다.

Python의 strbytes 타입과, osos.path 모듈의 일부는 C로 작성되어 매우 빠릅니다. pathlib은 순수 Python으로 작성되었고 종종 느리지만, 무시할 정도로 느린 경우는 드뭅니다.

pathlib’s path normalization is slightly more opinionated and consistent than os.path. For example, whereas os.path.abspath() eliminates “..” segments from a path, which may change its meaning if symlinks are involved, Path.absolute() preserves these segments for greater safety.

pathlib의 경로 정규화는 일부 애플리케이션에 적합하지 않을 수 있습니다:

  1. pathlib normalizes Path("my_folder/") to Path("my_folder"), which changes a path’s meaning when supplied to various operating system APIs and command-line utilities. Specifically, the absence of a trailing separator may allow the path to be resolved as either a file or directory, rather than a directory only.

  2. pathlib normalizes Path("./my_program") to Path("my_program"), which changes a path’s meaning when used as an executable search path, such as in a shell or when spawning a child process. Specifically, the absence of a separator in the path may force it to be looked up in PATH rather than the current directory.

As a consequence of these differences, pathlib is not a drop-in replacement for os.path.

대응되는 도구들

아래는 다양한 os 함수를 해당 PurePath/Path 대응 물에 매핑하는 표입니다.

os and os.path

pathlib

os.path.dirname()

PurePath.parent

os.path.basename()

PurePath.name

os.path.splitext()

PurePath.stem, PurePath.suffix

os.path.join()

PurePath.joinpath()

os.path.isabs()

PurePath.is_absolute()

os.path.relpath()

PurePath.relative_to() [1]

os.path.expanduser()

Path.expanduser() [2]

os.path.realpath()

Path.resolve()

os.path.abspath()

Path.absolute() [3]

os.path.exists()

Path.exists()

os.path.isfile()

Path.is_file()

os.path.isdir()

Path.is_dir()

os.path.islink()

Path.is_symlink()

os.path.isjunction()

Path.is_junction()

os.path.ismount()

Path.is_mount()

os.path.samefile()

Path.samefile()

os.getcwd()

Path.cwd()

os.stat()

Path.stat()

os.lstat()

Path.lstat()

os.listdir()

Path.iterdir()

os.walk()

Path.walk() [4]

os.mkdir(), os.makedirs()

Path.mkdir()

os.link()

Path.hardlink_to()

os.symlink()

Path.symlink_to()

os.readlink()

Path.readlink()

os.rename()

Path.rename()

os.replace()

Path.replace()

os.remove(), os.unlink()

Path.unlink()

os.rmdir()

Path.rmdir()

os.chmod()

Path.chmod()

os.lchmod()

Path.lchmod()

각주

프로토콜

pathlib.types 모듈은 정적 형 검사기를 위한 타입을 제공합니다.

Added in version 3.14.

class pathlib.types.PathInfo

A typing.Protocol describing the Path.info attribute. Implementations may return cached results from their methods.

exists(*, follow_symlinks=True)

경로가 존재하는 파일이나 디렉터리, 또는 다른 종류의 파일을 가리키면 True 를; 경로가 존재하지 않으면 False 를 반환합니다.

follow_symlinksFalse 인 경우, 대상이 존재하는지 확인하지 않고도 심볼릭 링크에 대해 True 를 반환합니다.

is_dir(*, follow_symlinks=True)

경로가 디렉터리이거나 디렉터리를 가리키는 심볼릭 링크이면 True 를; 경로가 (또는 다른 종류의 파일이거나) 또는 존재하지 않으면 False 를 반환합니다.

follow_symlinksFalse 인 경우, 경로가 디렉터리일 때만 (심볼릭 링크를 따라가지 않고) True 를; 경로가 다른 종류의 파일이거나 존재하지 않으면 False 를 반환합니다.

is_file(*, follow_symlinks=True)

경로가 파일이거나 파일을 가리키는 심볼릭 링크이면 True 를; 경로가 (또는 다른 종류의) 디렉터리나 비파일 항목이거나, 존재하지 않으면 False 를 반환합니다.

follow_symlinksFalse 인 경우, 경로가 파일일 때만 (심볼릭 링크를 따라가지 않고) True 를; 경로가 디렉터리이거나 다른 비파일 항목이거나, 존재하지 않으면 False 를 반환합니다.

경로가 심볼릭 링크이면 (손상되었더라도) True 를; 경로가 디렉터리나 어떤 종류의 파일이거나, 존재하지 않으면 False 를 반환합니다.

분실물 보관소