pathlib.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. """Object-oriented filesystem paths.
  2. This module provides classes to represent abstract paths and concrete
  3. paths with operations that have semantics appropriate for different
  4. operating systems.
  5. """
  6. import fnmatch
  7. import functools
  8. import io
  9. import ntpath
  10. import os
  11. import posixpath
  12. import re
  13. import sys
  14. import warnings
  15. from _collections_abc import Sequence
  16. from errno import ENOENT, ENOTDIR, EBADF, ELOOP
  17. from stat import S_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO
  18. from urllib.parse import quote_from_bytes as urlquote_from_bytes
  19. __all__ = [
  20. "PurePath", "PurePosixPath", "PureWindowsPath",
  21. "Path", "PosixPath", "WindowsPath",
  22. ]
  23. #
  24. # Internals
  25. #
  26. # Reference for Windows paths can be found at
  27. # https://learn.microsoft.com/en-gb/windows/win32/fileio/naming-a-file .
  28. _WIN_RESERVED_NAMES = frozenset(
  29. {'CON', 'PRN', 'AUX', 'NUL', 'CONIN$', 'CONOUT$'} |
  30. {f'COM{c}' for c in '123456789\xb9\xb2\xb3'} |
  31. {f'LPT{c}' for c in '123456789\xb9\xb2\xb3'}
  32. )
  33. _WINERROR_NOT_READY = 21 # drive exists but is not accessible
  34. _WINERROR_INVALID_NAME = 123 # fix for bpo-35306
  35. _WINERROR_CANT_RESOLVE_FILENAME = 1921 # broken symlink pointing to itself
  36. # EBADF - guard against macOS `stat` throwing EBADF
  37. _IGNORED_ERRNOS = (ENOENT, ENOTDIR, EBADF, ELOOP)
  38. _IGNORED_WINERRORS = (
  39. _WINERROR_NOT_READY,
  40. _WINERROR_INVALID_NAME,
  41. _WINERROR_CANT_RESOLVE_FILENAME)
  42. def _ignore_error(exception):
  43. return (getattr(exception, 'errno', None) in _IGNORED_ERRNOS or
  44. getattr(exception, 'winerror', None) in _IGNORED_WINERRORS)
  45. @functools.cache
  46. def _is_case_sensitive(flavour):
  47. return flavour.normcase('Aa') == 'Aa'
  48. #
  49. # Globbing helpers
  50. #
  51. # fnmatch.translate() returns a regular expression that includes a prefix and
  52. # a suffix, which enable matching newlines and ensure the end of the string is
  53. # matched, respectively. These features are undesirable for our implementation
  54. # of PurePatch.match(), which represents path separators as newlines and joins
  55. # pattern segments together. As a workaround, we define a slice object that
  56. # can remove the prefix and suffix from any translate() result. See the
  57. # _compile_pattern_lines() function for more details.
  58. _FNMATCH_PREFIX, _FNMATCH_SUFFIX = fnmatch.translate('_').split('_')
  59. _FNMATCH_SLICE = slice(len(_FNMATCH_PREFIX), -len(_FNMATCH_SUFFIX))
  60. _SWAP_SEP_AND_NEWLINE = {
  61. '/': str.maketrans({'/': '\n', '\n': '/'}),
  62. '\\': str.maketrans({'\\': '\n', '\n': '\\'}),
  63. }
  64. @functools.lru_cache()
  65. def _make_selector(pattern_parts, flavour, case_sensitive):
  66. pat = pattern_parts[0]
  67. if not pat:
  68. return _TerminatingSelector()
  69. if pat == '**':
  70. child_parts_idx = 1
  71. while child_parts_idx < len(pattern_parts) and pattern_parts[child_parts_idx] == '**':
  72. child_parts_idx += 1
  73. child_parts = pattern_parts[child_parts_idx:]
  74. if '**' in child_parts:
  75. cls = _DoubleRecursiveWildcardSelector
  76. else:
  77. cls = _RecursiveWildcardSelector
  78. else:
  79. child_parts = pattern_parts[1:]
  80. if pat == '..':
  81. cls = _ParentSelector
  82. elif '**' in pat:
  83. raise ValueError("Invalid pattern: '**' can only be an entire path component")
  84. else:
  85. cls = _WildcardSelector
  86. return cls(pat, child_parts, flavour, case_sensitive)
  87. @functools.lru_cache(maxsize=256)
  88. def _compile_pattern(pat, case_sensitive):
  89. flags = re.NOFLAG if case_sensitive else re.IGNORECASE
  90. return re.compile(fnmatch.translate(pat), flags).match
  91. @functools.lru_cache()
  92. def _compile_pattern_lines(pattern_lines, case_sensitive):
  93. """Compile the given pattern lines to an `re.Pattern` object.
  94. The *pattern_lines* argument is a glob-style pattern (e.g. '*/*.py') with
  95. its path separators and newlines swapped (e.g. '*\n*.py`). By using
  96. newlines to separate path components, and not setting `re.DOTALL`, we
  97. ensure that the `*` wildcard cannot match path separators.
  98. The returned `re.Pattern` object may have its `match()` method called to
  99. match a complete pattern, or `search()` to match from the right. The
  100. argument supplied to these methods must also have its path separators and
  101. newlines swapped.
  102. """
  103. # Match the start of the path, or just after a path separator
  104. parts = ['^']
  105. for part in pattern_lines.splitlines(keepends=True):
  106. if part == '*\n':
  107. part = r'.+\n'
  108. elif part == '*':
  109. part = r'.+'
  110. else:
  111. # Any other component: pass to fnmatch.translate(). We slice off
  112. # the common prefix and suffix added by translate() to ensure that
  113. # re.DOTALL is not set, and the end of the string not matched,
  114. # respectively. With DOTALL not set, '*' wildcards will not match
  115. # path separators, because the '.' characters in the pattern will
  116. # not match newlines.
  117. part = fnmatch.translate(part)[_FNMATCH_SLICE]
  118. parts.append(part)
  119. # Match the end of the path, always.
  120. parts.append(r'\Z')
  121. flags = re.MULTILINE
  122. if not case_sensitive:
  123. flags |= re.IGNORECASE
  124. return re.compile(''.join(parts), flags=flags)
  125. class _Selector:
  126. """A selector matches a specific glob pattern part against the children
  127. of a given path."""
  128. def __init__(self, child_parts, flavour, case_sensitive):
  129. self.child_parts = child_parts
  130. if child_parts:
  131. self.successor = _make_selector(child_parts, flavour, case_sensitive)
  132. self.dironly = True
  133. else:
  134. self.successor = _TerminatingSelector()
  135. self.dironly = False
  136. def select_from(self, parent_path):
  137. """Iterate over all child paths of `parent_path` matched by this
  138. selector. This can contain parent_path itself."""
  139. path_cls = type(parent_path)
  140. scandir = path_cls._scandir
  141. if not parent_path.is_dir():
  142. return iter([])
  143. return self._select_from(parent_path, scandir)
  144. class _TerminatingSelector:
  145. def _select_from(self, parent_path, scandir):
  146. yield parent_path
  147. class _ParentSelector(_Selector):
  148. def __init__(self, name, child_parts, flavour, case_sensitive):
  149. _Selector.__init__(self, child_parts, flavour, case_sensitive)
  150. def _select_from(self, parent_path, scandir):
  151. path = parent_path._make_child_relpath('..')
  152. for p in self.successor._select_from(path, scandir):
  153. yield p
  154. class _WildcardSelector(_Selector):
  155. def __init__(self, pat, child_parts, flavour, case_sensitive):
  156. _Selector.__init__(self, child_parts, flavour, case_sensitive)
  157. if case_sensitive is None:
  158. # TODO: evaluate case-sensitivity of each directory in _select_from()
  159. case_sensitive = _is_case_sensitive(flavour)
  160. self.match = _compile_pattern(pat, case_sensitive)
  161. def _select_from(self, parent_path, scandir):
  162. try:
  163. # We must close the scandir() object before proceeding to
  164. # avoid exhausting file descriptors when globbing deep trees.
  165. with scandir(parent_path) as scandir_it:
  166. entries = list(scandir_it)
  167. except OSError:
  168. pass
  169. else:
  170. for entry in entries:
  171. if self.dironly:
  172. try:
  173. if not entry.is_dir():
  174. continue
  175. except OSError:
  176. continue
  177. name = entry.name
  178. if self.match(name):
  179. path = parent_path._make_child_relpath(name)
  180. for p in self.successor._select_from(path, scandir):
  181. yield p
  182. class _RecursiveWildcardSelector(_Selector):
  183. def __init__(self, pat, child_parts, flavour, case_sensitive):
  184. _Selector.__init__(self, child_parts, flavour, case_sensitive)
  185. def _iterate_directories(self, parent_path):
  186. yield parent_path
  187. for dirpath, dirnames, _ in parent_path.walk():
  188. for dirname in dirnames:
  189. yield dirpath._make_child_relpath(dirname)
  190. def _select_from(self, parent_path, scandir):
  191. successor_select = self.successor._select_from
  192. for starting_point in self._iterate_directories(parent_path):
  193. for p in successor_select(starting_point, scandir):
  194. yield p
  195. class _DoubleRecursiveWildcardSelector(_RecursiveWildcardSelector):
  196. """
  197. Like _RecursiveWildcardSelector, but also de-duplicates results from
  198. successive selectors. This is necessary if the pattern contains
  199. multiple non-adjacent '**' segments.
  200. """
  201. def _select_from(self, parent_path, scandir):
  202. yielded = set()
  203. try:
  204. for p in super()._select_from(parent_path, scandir):
  205. if p not in yielded:
  206. yield p
  207. yielded.add(p)
  208. finally:
  209. yielded.clear()
  210. #
  211. # Public API
  212. #
  213. class _PathParents(Sequence):
  214. """This object provides sequence-like access to the logical ancestors
  215. of a path. Don't try to construct it yourself."""
  216. __slots__ = ('_path', '_drv', '_root', '_tail')
  217. def __init__(self, path):
  218. self._path = path
  219. self._drv = path.drive
  220. self._root = path.root
  221. self._tail = path._tail
  222. def __len__(self):
  223. return len(self._tail)
  224. def __getitem__(self, idx):
  225. if isinstance(idx, slice):
  226. return tuple(self[i] for i in range(*idx.indices(len(self))))
  227. if idx >= len(self) or idx < -len(self):
  228. raise IndexError(idx)
  229. if idx < 0:
  230. idx += len(self)
  231. return self._path._from_parsed_parts(self._drv, self._root,
  232. self._tail[:-idx - 1])
  233. def __repr__(self):
  234. return "<{}.parents>".format(type(self._path).__name__)
  235. class PurePath(object):
  236. """Base class for manipulating paths without I/O.
  237. PurePath represents a filesystem path and offers operations which
  238. don't imply any actual filesystem I/O. Depending on your system,
  239. instantiating a PurePath will return either a PurePosixPath or a
  240. PureWindowsPath object. You can also instantiate either of these classes
  241. directly, regardless of your system.
  242. """
  243. __slots__ = (
  244. # The `_raw_paths` slot stores unnormalized string paths. This is set
  245. # in the `__init__()` method.
  246. '_raw_paths',
  247. # The `_drv`, `_root` and `_tail_cached` slots store parsed and
  248. # normalized parts of the path. They are set when any of the `drive`,
  249. # `root` or `_tail` properties are accessed for the first time. The
  250. # three-part division corresponds to the result of
  251. # `os.path.splitroot()`, except that the tail is further split on path
  252. # separators (i.e. it is a list of strings), and that the root and
  253. # tail are normalized.
  254. '_drv', '_root', '_tail_cached',
  255. # The `_str` slot stores the string representation of the path,
  256. # computed from the drive, root and tail when `__str__()` is called
  257. # for the first time. It's used to implement `_str_normcase`
  258. '_str',
  259. # The `_str_normcase_cached` slot stores the string path with
  260. # normalized case. It is set when the `_str_normcase` property is
  261. # accessed for the first time. It's used to implement `__eq__()`
  262. # `__hash__()`, and `_parts_normcase`
  263. '_str_normcase_cached',
  264. # The `_parts_normcase_cached` slot stores the case-normalized
  265. # string path after splitting on path separators. It's set when the
  266. # `_parts_normcase` property is accessed for the first time. It's used
  267. # to implement comparison methods like `__lt__()`.
  268. '_parts_normcase_cached',
  269. # The `_lines_cached` slot stores the string path with path separators
  270. # and newlines swapped. This is used to implement `match()`.
  271. '_lines_cached',
  272. # The `_hash` slot stores the hash of the case-normalized string
  273. # path. It's set when `__hash__()` is called for the first time.
  274. '_hash',
  275. )
  276. _flavour = os.path
  277. def __new__(cls, *args, **kwargs):
  278. """Construct a PurePath from one or several strings and or existing
  279. PurePath objects. The strings and path objects are combined so as
  280. to yield a canonicalized path, which is incorporated into the
  281. new PurePath object.
  282. """
  283. if cls is PurePath:
  284. cls = PureWindowsPath if os.name == 'nt' else PurePosixPath
  285. return object.__new__(cls)
  286. def __reduce__(self):
  287. # Using the parts tuple helps share interned path parts
  288. # when pickling related paths.
  289. return (self.__class__, self.parts)
  290. def __init__(self, *args):
  291. paths = []
  292. for arg in args:
  293. if isinstance(arg, PurePath):
  294. if arg._flavour is ntpath and self._flavour is posixpath:
  295. # GH-103631: Convert separators for backwards compatibility.
  296. paths.extend(path.replace('\\', '/') for path in arg._raw_paths)
  297. else:
  298. paths.extend(arg._raw_paths)
  299. else:
  300. try:
  301. path = os.fspath(arg)
  302. except TypeError:
  303. path = arg
  304. if not isinstance(path, str):
  305. raise TypeError(
  306. "argument should be a str or an os.PathLike "
  307. "object where __fspath__ returns a str, "
  308. f"not {type(path).__name__!r}")
  309. paths.append(path)
  310. self._raw_paths = paths
  311. def with_segments(self, *pathsegments):
  312. """Construct a new path object from any number of path-like objects.
  313. Subclasses may override this method to customize how new path objects
  314. are created from methods like `iterdir()`.
  315. """
  316. return type(self)(*pathsegments)
  317. @classmethod
  318. def _parse_path(cls, path):
  319. if not path:
  320. return '', '', []
  321. sep = cls._flavour.sep
  322. altsep = cls._flavour.altsep
  323. if altsep:
  324. path = path.replace(altsep, sep)
  325. drv, root, rel = cls._flavour.splitroot(path)
  326. if not root and drv.startswith(sep) and not drv.endswith(sep):
  327. drv_parts = drv.split(sep)
  328. if len(drv_parts) == 4 and drv_parts[2] not in '?.':
  329. # e.g. //server/share
  330. root = sep
  331. elif len(drv_parts) == 6:
  332. # e.g. //?/unc/server/share
  333. root = sep
  334. parsed = [sys.intern(str(x)) for x in rel.split(sep) if x and x != '.']
  335. return drv, root, parsed
  336. def _load_parts(self):
  337. paths = self._raw_paths
  338. if len(paths) == 0:
  339. path = ''
  340. elif len(paths) == 1:
  341. path = paths[0]
  342. else:
  343. path = self._flavour.join(*paths)
  344. drv, root, tail = self._parse_path(path)
  345. self._drv = drv
  346. self._root = root
  347. self._tail_cached = tail
  348. def _from_parsed_parts(self, drv, root, tail):
  349. path_str = self._format_parsed_parts(drv, root, tail)
  350. path = self.with_segments(path_str)
  351. path._str = path_str or '.'
  352. path._drv = drv
  353. path._root = root
  354. path._tail_cached = tail
  355. return path
  356. @classmethod
  357. def _format_parsed_parts(cls, drv, root, tail):
  358. if drv or root:
  359. return drv + root + cls._flavour.sep.join(tail)
  360. elif tail and cls._flavour.splitdrive(tail[0])[0]:
  361. tail = ['.'] + tail
  362. return cls._flavour.sep.join(tail)
  363. def __str__(self):
  364. """Return the string representation of the path, suitable for
  365. passing to system calls."""
  366. try:
  367. return self._str
  368. except AttributeError:
  369. self._str = self._format_parsed_parts(self.drive, self.root,
  370. self._tail) or '.'
  371. return self._str
  372. def __fspath__(self):
  373. return str(self)
  374. def as_posix(self):
  375. """Return the string representation of the path with forward (/)
  376. slashes."""
  377. f = self._flavour
  378. return str(self).replace(f.sep, '/')
  379. def __bytes__(self):
  380. """Return the bytes representation of the path. This is only
  381. recommended to use under Unix."""
  382. return os.fsencode(self)
  383. def __repr__(self):
  384. return "{}({!r})".format(self.__class__.__name__, self.as_posix())
  385. def as_uri(self):
  386. """Return the path as a 'file' URI."""
  387. if not self.is_absolute():
  388. raise ValueError("relative path can't be expressed as a file URI")
  389. drive = self.drive
  390. if len(drive) == 2 and drive[1] == ':':
  391. # It's a path on a local drive => 'file:///c:/a/b'
  392. prefix = 'file:///' + drive
  393. path = self.as_posix()[2:]
  394. elif drive:
  395. # It's a path on a network drive => 'file://host/share/a/b'
  396. prefix = 'file:'
  397. path = self.as_posix()
  398. else:
  399. # It's a posix path => 'file:///etc/hosts'
  400. prefix = 'file://'
  401. path = str(self)
  402. return prefix + urlquote_from_bytes(os.fsencode(path))
  403. @property
  404. def _str_normcase(self):
  405. # String with normalized case, for hashing and equality checks
  406. try:
  407. return self._str_normcase_cached
  408. except AttributeError:
  409. if _is_case_sensitive(self._flavour):
  410. self._str_normcase_cached = str(self)
  411. else:
  412. self._str_normcase_cached = str(self).lower()
  413. return self._str_normcase_cached
  414. @property
  415. def _parts_normcase(self):
  416. # Cached parts with normalized case, for comparisons.
  417. try:
  418. return self._parts_normcase_cached
  419. except AttributeError:
  420. self._parts_normcase_cached = self._str_normcase.split(self._flavour.sep)
  421. return self._parts_normcase_cached
  422. @property
  423. def _lines(self):
  424. # Path with separators and newlines swapped, for pattern matching.
  425. try:
  426. return self._lines_cached
  427. except AttributeError:
  428. path_str = str(self)
  429. if path_str == '.':
  430. self._lines_cached = ''
  431. else:
  432. trans = _SWAP_SEP_AND_NEWLINE[self._flavour.sep]
  433. self._lines_cached = path_str.translate(trans)
  434. return self._lines_cached
  435. def __eq__(self, other):
  436. if not isinstance(other, PurePath):
  437. return NotImplemented
  438. return self._str_normcase == other._str_normcase and self._flavour is other._flavour
  439. def __hash__(self):
  440. try:
  441. return self._hash
  442. except AttributeError:
  443. self._hash = hash(self._str_normcase)
  444. return self._hash
  445. def __lt__(self, other):
  446. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  447. return NotImplemented
  448. return self._parts_normcase < other._parts_normcase
  449. def __le__(self, other):
  450. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  451. return NotImplemented
  452. return self._parts_normcase <= other._parts_normcase
  453. def __gt__(self, other):
  454. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  455. return NotImplemented
  456. return self._parts_normcase > other._parts_normcase
  457. def __ge__(self, other):
  458. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  459. return NotImplemented
  460. return self._parts_normcase >= other._parts_normcase
  461. @property
  462. def drive(self):
  463. """The drive prefix (letter or UNC path), if any."""
  464. try:
  465. return self._drv
  466. except AttributeError:
  467. self._load_parts()
  468. return self._drv
  469. @property
  470. def root(self):
  471. """The root of the path, if any."""
  472. try:
  473. return self._root
  474. except AttributeError:
  475. self._load_parts()
  476. return self._root
  477. @property
  478. def _tail(self):
  479. try:
  480. return self._tail_cached
  481. except AttributeError:
  482. self._load_parts()
  483. return self._tail_cached
  484. @property
  485. def anchor(self):
  486. """The concatenation of the drive and root, or ''."""
  487. anchor = self.drive + self.root
  488. return anchor
  489. @property
  490. def name(self):
  491. """The final path component, if any."""
  492. tail = self._tail
  493. if not tail:
  494. return ''
  495. return tail[-1]
  496. @property
  497. def suffix(self):
  498. """
  499. The final component's last suffix, if any.
  500. This includes the leading period. For example: '.txt'
  501. """
  502. name = self.name
  503. i = name.rfind('.')
  504. if 0 < i < len(name) - 1:
  505. return name[i:]
  506. else:
  507. return ''
  508. @property
  509. def suffixes(self):
  510. """
  511. A list of the final component's suffixes, if any.
  512. These include the leading periods. For example: ['.tar', '.gz']
  513. """
  514. name = self.name
  515. if name.endswith('.'):
  516. return []
  517. name = name.lstrip('.')
  518. return ['.' + suffix for suffix in name.split('.')[1:]]
  519. @property
  520. def stem(self):
  521. """The final path component, minus its last suffix."""
  522. name = self.name
  523. i = name.rfind('.')
  524. if 0 < i < len(name) - 1:
  525. return name[:i]
  526. else:
  527. return name
  528. def with_name(self, name):
  529. """Return a new path with the file name changed."""
  530. if not self.name:
  531. raise ValueError("%r has an empty name" % (self,))
  532. f = self._flavour
  533. drv, root, tail = f.splitroot(name)
  534. if drv or root or not tail or f.sep in tail or (f.altsep and f.altsep in tail):
  535. raise ValueError("Invalid name %r" % (name))
  536. return self._from_parsed_parts(self.drive, self.root,
  537. self._tail[:-1] + [name])
  538. def with_stem(self, stem):
  539. """Return a new path with the stem changed."""
  540. return self.with_name(stem + self.suffix)
  541. def with_suffix(self, suffix):
  542. """Return a new path with the file suffix changed. If the path
  543. has no suffix, add given suffix. If the given suffix is an empty
  544. string, remove the suffix from the path.
  545. """
  546. f = self._flavour
  547. if f.sep in suffix or f.altsep and f.altsep in suffix:
  548. raise ValueError("Invalid suffix %r" % (suffix,))
  549. if suffix and not suffix.startswith('.') or suffix == '.':
  550. raise ValueError("Invalid suffix %r" % (suffix))
  551. name = self.name
  552. if not name:
  553. raise ValueError("%r has an empty name" % (self,))
  554. old_suffix = self.suffix
  555. if not old_suffix:
  556. name = name + suffix
  557. else:
  558. name = name[:-len(old_suffix)] + suffix
  559. return self._from_parsed_parts(self.drive, self.root,
  560. self._tail[:-1] + [name])
  561. def relative_to(self, other, /, *_deprecated, walk_up=False):
  562. """Return the relative path to another path identified by the passed
  563. arguments. If the operation is not possible (because this is not
  564. related to the other path), raise ValueError.
  565. The *walk_up* parameter controls whether `..` may be used to resolve
  566. the path.
  567. """
  568. if _deprecated:
  569. msg = ("support for supplying more than one positional argument "
  570. "to pathlib.PurePath.relative_to() is deprecated and "
  571. "scheduled for removal in Python {remove}")
  572. warnings._deprecated("pathlib.PurePath.relative_to(*args)", msg,
  573. remove=(3, 14))
  574. other = self.with_segments(other, *_deprecated)
  575. for step, path in enumerate([other] + list(other.parents)):
  576. if self.is_relative_to(path):
  577. break
  578. elif not walk_up:
  579. raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
  580. elif path.name == '..':
  581. raise ValueError(f"'..' segment in {str(other)!r} cannot be walked")
  582. else:
  583. raise ValueError(f"{str(self)!r} and {str(other)!r} have different anchors")
  584. parts = ['..'] * step + self._tail[len(path._tail):]
  585. return self.with_segments(*parts)
  586. def is_relative_to(self, other, /, *_deprecated):
  587. """Return True if the path is relative to another path or False.
  588. """
  589. if _deprecated:
  590. msg = ("support for supplying more than one argument to "
  591. "pathlib.PurePath.is_relative_to() is deprecated and "
  592. "scheduled for removal in Python {remove}")
  593. warnings._deprecated("pathlib.PurePath.is_relative_to(*args)",
  594. msg, remove=(3, 14))
  595. other = self.with_segments(other, *_deprecated)
  596. return other == self or other in self.parents
  597. @property
  598. def parts(self):
  599. """An object providing sequence-like access to the
  600. components in the filesystem path."""
  601. if self.drive or self.root:
  602. return (self.drive + self.root,) + tuple(self._tail)
  603. else:
  604. return tuple(self._tail)
  605. def joinpath(self, *pathsegments):
  606. """Combine this path with one or several arguments, and return a
  607. new path representing either a subpath (if all arguments are relative
  608. paths) or a totally different path (if one of the arguments is
  609. anchored).
  610. """
  611. return self.with_segments(self, *pathsegments)
  612. def __truediv__(self, key):
  613. try:
  614. return self.joinpath(key)
  615. except TypeError:
  616. return NotImplemented
  617. def __rtruediv__(self, key):
  618. try:
  619. return self.with_segments(key, self)
  620. except TypeError:
  621. return NotImplemented
  622. @property
  623. def parent(self):
  624. """The logical parent of the path."""
  625. drv = self.drive
  626. root = self.root
  627. tail = self._tail
  628. if not tail:
  629. return self
  630. return self._from_parsed_parts(drv, root, tail[:-1])
  631. @property
  632. def parents(self):
  633. """A sequence of this path's logical parents."""
  634. # The value of this property should not be cached on the path object,
  635. # as doing so would introduce a reference cycle.
  636. return _PathParents(self)
  637. def is_absolute(self):
  638. """True if the path is absolute (has both a root and, if applicable,
  639. a drive)."""
  640. if self._flavour is ntpath:
  641. # ntpath.isabs() is defective - see GH-44626.
  642. return bool(self.drive and self.root)
  643. elif self._flavour is posixpath:
  644. # Optimization: work with raw paths on POSIX.
  645. for path in self._raw_paths:
  646. if path.startswith('/'):
  647. return True
  648. return False
  649. else:
  650. return self._flavour.isabs(str(self))
  651. def is_reserved(self):
  652. """Return True if the path contains one of the special names reserved
  653. by the system, if any."""
  654. if self._flavour is posixpath or not self._tail:
  655. return False
  656. # NOTE: the rules for reserved names seem somewhat complicated
  657. # (e.g. r"..\NUL" is reserved but not r"foo\NUL" if "foo" does not
  658. # exist). We err on the side of caution and return True for paths
  659. # which are not considered reserved by Windows.
  660. if self.drive.startswith('\\\\'):
  661. # UNC paths are never reserved.
  662. return False
  663. name = self._tail[-1].partition('.')[0].partition(':')[0].rstrip(' ')
  664. return name.upper() in _WIN_RESERVED_NAMES
  665. def match(self, path_pattern, *, case_sensitive=None):
  666. """
  667. Return True if this path matches the given pattern.
  668. """
  669. if not isinstance(path_pattern, PurePath):
  670. path_pattern = self.with_segments(path_pattern)
  671. if case_sensitive is None:
  672. case_sensitive = _is_case_sensitive(self._flavour)
  673. pattern = _compile_pattern_lines(path_pattern._lines, case_sensitive)
  674. if path_pattern.drive or path_pattern.root:
  675. return pattern.match(self._lines) is not None
  676. elif path_pattern._tail:
  677. return pattern.search(self._lines) is not None
  678. else:
  679. raise ValueError("empty pattern")
  680. # Can't subclass os.PathLike from PurePath and keep the constructor
  681. # optimizations in PurePath.__slots__.
  682. os.PathLike.register(PurePath)
  683. class PurePosixPath(PurePath):
  684. """PurePath subclass for non-Windows systems.
  685. On a POSIX system, instantiating a PurePath should return this object.
  686. However, you can also instantiate it directly on any system.
  687. """
  688. _flavour = posixpath
  689. __slots__ = ()
  690. class PureWindowsPath(PurePath):
  691. """PurePath subclass for Windows systems.
  692. On a Windows system, instantiating a PurePath should return this object.
  693. However, you can also instantiate it directly on any system.
  694. """
  695. _flavour = ntpath
  696. __slots__ = ()
  697. # Filesystem-accessing classes
  698. class Path(PurePath):
  699. """PurePath subclass that can make system calls.
  700. Path represents a filesystem path but unlike PurePath, also offers
  701. methods to do system calls on path objects. Depending on your system,
  702. instantiating a Path will return either a PosixPath or a WindowsPath
  703. object. You can also instantiate a PosixPath or WindowsPath directly,
  704. but cannot instantiate a WindowsPath on a POSIX system or vice versa.
  705. """
  706. __slots__ = ()
  707. def stat(self, *, follow_symlinks=True):
  708. """
  709. Return the result of the stat() system call on this path, like
  710. os.stat() does.
  711. """
  712. return os.stat(self, follow_symlinks=follow_symlinks)
  713. def lstat(self):
  714. """
  715. Like stat(), except if the path points to a symlink, the symlink's
  716. status information is returned, rather than its target's.
  717. """
  718. return self.stat(follow_symlinks=False)
  719. # Convenience functions for querying the stat results
  720. def exists(self, *, follow_symlinks=True):
  721. """
  722. Whether this path exists.
  723. This method normally follows symlinks; to check whether a symlink exists,
  724. add the argument follow_symlinks=False.
  725. """
  726. try:
  727. self.stat(follow_symlinks=follow_symlinks)
  728. except OSError as e:
  729. if not _ignore_error(e):
  730. raise
  731. return False
  732. except ValueError:
  733. # Non-encodable path
  734. return False
  735. return True
  736. def is_dir(self):
  737. """
  738. Whether this path is a directory.
  739. """
  740. try:
  741. return S_ISDIR(self.stat().st_mode)
  742. except OSError as e:
  743. if not _ignore_error(e):
  744. raise
  745. # Path doesn't exist or is a broken symlink
  746. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  747. return False
  748. except ValueError:
  749. # Non-encodable path
  750. return False
  751. def is_file(self):
  752. """
  753. Whether this path is a regular file (also True for symlinks pointing
  754. to regular files).
  755. """
  756. try:
  757. return S_ISREG(self.stat().st_mode)
  758. except OSError as e:
  759. if not _ignore_error(e):
  760. raise
  761. # Path doesn't exist or is a broken symlink
  762. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  763. return False
  764. except ValueError:
  765. # Non-encodable path
  766. return False
  767. def is_mount(self):
  768. """
  769. Check if this path is a mount point
  770. """
  771. return self._flavour.ismount(self)
  772. def is_symlink(self):
  773. """
  774. Whether this path is a symbolic link.
  775. """
  776. try:
  777. return S_ISLNK(self.lstat().st_mode)
  778. except OSError as e:
  779. if not _ignore_error(e):
  780. raise
  781. # Path doesn't exist
  782. return False
  783. except ValueError:
  784. # Non-encodable path
  785. return False
  786. def is_junction(self):
  787. """
  788. Whether this path is a junction.
  789. """
  790. return self._flavour.isjunction(self)
  791. def is_block_device(self):
  792. """
  793. Whether this path is a block device.
  794. """
  795. try:
  796. return S_ISBLK(self.stat().st_mode)
  797. except OSError as e:
  798. if not _ignore_error(e):
  799. raise
  800. # Path doesn't exist or is a broken symlink
  801. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  802. return False
  803. except ValueError:
  804. # Non-encodable path
  805. return False
  806. def is_char_device(self):
  807. """
  808. Whether this path is a character device.
  809. """
  810. try:
  811. return S_ISCHR(self.stat().st_mode)
  812. except OSError as e:
  813. if not _ignore_error(e):
  814. raise
  815. # Path doesn't exist or is a broken symlink
  816. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  817. return False
  818. except ValueError:
  819. # Non-encodable path
  820. return False
  821. def is_fifo(self):
  822. """
  823. Whether this path is a FIFO.
  824. """
  825. try:
  826. return S_ISFIFO(self.stat().st_mode)
  827. except OSError as e:
  828. if not _ignore_error(e):
  829. raise
  830. # Path doesn't exist or is a broken symlink
  831. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  832. return False
  833. except ValueError:
  834. # Non-encodable path
  835. return False
  836. def is_socket(self):
  837. """
  838. Whether this path is a socket.
  839. """
  840. try:
  841. return S_ISSOCK(self.stat().st_mode)
  842. except OSError as e:
  843. if not _ignore_error(e):
  844. raise
  845. # Path doesn't exist or is a broken symlink
  846. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  847. return False
  848. except ValueError:
  849. # Non-encodable path
  850. return False
  851. def samefile(self, other_path):
  852. """Return whether other_path is the same or not as this file
  853. (as returned by os.path.samefile()).
  854. """
  855. st = self.stat()
  856. try:
  857. other_st = other_path.stat()
  858. except AttributeError:
  859. other_st = self.with_segments(other_path).stat()
  860. return self._flavour.samestat(st, other_st)
  861. def open(self, mode='r', buffering=-1, encoding=None,
  862. errors=None, newline=None):
  863. """
  864. Open the file pointed by this path and return a file object, as
  865. the built-in open() function does.
  866. """
  867. if "b" not in mode:
  868. encoding = io.text_encoding(encoding)
  869. return io.open(self, mode, buffering, encoding, errors, newline)
  870. def read_bytes(self):
  871. """
  872. Open the file in bytes mode, read it, and close the file.
  873. """
  874. with self.open(mode='rb') as f:
  875. return f.read()
  876. def read_text(self, encoding=None, errors=None):
  877. """
  878. Open the file in text mode, read it, and close the file.
  879. """
  880. encoding = io.text_encoding(encoding)
  881. with self.open(mode='r', encoding=encoding, errors=errors) as f:
  882. return f.read()
  883. def write_bytes(self, data):
  884. """
  885. Open the file in bytes mode, write to it, and close the file.
  886. """
  887. # type-check for the buffer interface before truncating the file
  888. view = memoryview(data)
  889. with self.open(mode='wb') as f:
  890. return f.write(view)
  891. def write_text(self, data, encoding=None, errors=None, newline=None):
  892. """
  893. Open the file in text mode, write to it, and close the file.
  894. """
  895. if not isinstance(data, str):
  896. raise TypeError('data must be str, not %s' %
  897. data.__class__.__name__)
  898. encoding = io.text_encoding(encoding)
  899. with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
  900. return f.write(data)
  901. def iterdir(self):
  902. """Yield path objects of the directory contents.
  903. The children are yielded in arbitrary order, and the
  904. special entries '.' and '..' are not included.
  905. """
  906. for name in os.listdir(self):
  907. yield self._make_child_relpath(name)
  908. def _scandir(self):
  909. # bpo-24132: a future version of pathlib will support subclassing of
  910. # pathlib.Path to customize how the filesystem is accessed. This
  911. # includes scandir(), which is used to implement glob().
  912. return os.scandir(self)
  913. def _make_child_relpath(self, name):
  914. path_str = str(self)
  915. tail = self._tail
  916. if tail:
  917. path_str = f'{path_str}{self._flavour.sep}{name}'
  918. elif path_str != '.':
  919. path_str = f'{path_str}{name}'
  920. else:
  921. path_str = name
  922. path = self.with_segments(path_str)
  923. path._str = path_str
  924. path._drv = self.drive
  925. path._root = self.root
  926. path._tail_cached = tail + [name]
  927. return path
  928. def glob(self, pattern, *, case_sensitive=None):
  929. """Iterate over this subtree and yield all existing files (of any
  930. kind, including directories) matching the given relative pattern.
  931. """
  932. sys.audit("pathlib.Path.glob", self, pattern)
  933. if not pattern:
  934. raise ValueError("Unacceptable pattern: {!r}".format(pattern))
  935. drv, root, pattern_parts = self._parse_path(pattern)
  936. if drv or root:
  937. raise NotImplementedError("Non-relative patterns are unsupported")
  938. if pattern[-1] in (self._flavour.sep, self._flavour.altsep):
  939. pattern_parts.append('')
  940. selector = _make_selector(tuple(pattern_parts), self._flavour, case_sensitive)
  941. for p in selector.select_from(self):
  942. yield p
  943. def rglob(self, pattern, *, case_sensitive=None):
  944. """Recursively yield all existing files (of any kind, including
  945. directories) matching the given relative pattern, anywhere in
  946. this subtree.
  947. """
  948. sys.audit("pathlib.Path.rglob", self, pattern)
  949. drv, root, pattern_parts = self._parse_path(pattern)
  950. if drv or root:
  951. raise NotImplementedError("Non-relative patterns are unsupported")
  952. if pattern and pattern[-1] in (self._flavour.sep, self._flavour.altsep):
  953. pattern_parts.append('')
  954. selector = _make_selector(("**",) + tuple(pattern_parts), self._flavour, case_sensitive)
  955. for p in selector.select_from(self):
  956. yield p
  957. def walk(self, top_down=True, on_error=None, follow_symlinks=False):
  958. """Walk the directory tree from this directory, similar to os.walk()."""
  959. sys.audit("pathlib.Path.walk", self, on_error, follow_symlinks)
  960. paths = [self]
  961. while paths:
  962. path = paths.pop()
  963. if isinstance(path, tuple):
  964. yield path
  965. continue
  966. # We may not have read permission for self, in which case we can't
  967. # get a list of the files the directory contains. os.walk()
  968. # always suppressed the exception in that instance, rather than
  969. # blow up for a minor reason when (say) a thousand readable
  970. # directories are still left to visit. That logic is copied here.
  971. try:
  972. scandir_it = path._scandir()
  973. except OSError as error:
  974. if on_error is not None:
  975. on_error(error)
  976. continue
  977. with scandir_it:
  978. dirnames = []
  979. filenames = []
  980. for entry in scandir_it:
  981. try:
  982. is_dir = entry.is_dir(follow_symlinks=follow_symlinks)
  983. except OSError:
  984. # Carried over from os.path.isdir().
  985. is_dir = False
  986. if is_dir:
  987. dirnames.append(entry.name)
  988. else:
  989. filenames.append(entry.name)
  990. if top_down:
  991. yield path, dirnames, filenames
  992. else:
  993. paths.append((path, dirnames, filenames))
  994. paths += [path._make_child_relpath(d) for d in reversed(dirnames)]
  995. def __init__(self, *args, **kwargs):
  996. if kwargs:
  997. msg = ("support for supplying keyword arguments to pathlib.PurePath "
  998. "is deprecated and scheduled for removal in Python {remove}")
  999. warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
  1000. super().__init__(*args)
  1001. def __new__(cls, *args, **kwargs):
  1002. if cls is Path:
  1003. cls = WindowsPath if os.name == 'nt' else PosixPath
  1004. return object.__new__(cls)
  1005. def __enter__(self):
  1006. # In previous versions of pathlib, __exit__() marked this path as
  1007. # closed; subsequent attempts to perform I/O would raise an IOError.
  1008. # This functionality was never documented, and had the effect of
  1009. # making Path objects mutable, contrary to PEP 428.
  1010. # In Python 3.9 __exit__() was made a no-op.
  1011. # In Python 3.11 __enter__() began emitting DeprecationWarning.
  1012. # In Python 3.13 __enter__() and __exit__() should be removed.
  1013. warnings.warn("pathlib.Path.__enter__() is deprecated and scheduled "
  1014. "for removal in Python 3.13; Path objects as a context "
  1015. "manager is a no-op",
  1016. DeprecationWarning, stacklevel=2)
  1017. return self
  1018. def __exit__(self, t, v, tb):
  1019. pass
  1020. # Public API
  1021. @classmethod
  1022. def cwd(cls):
  1023. """Return a new path pointing to the current working directory."""
  1024. # We call 'absolute()' rather than using 'os.getcwd()' directly to
  1025. # enable users to replace the implementation of 'absolute()' in a
  1026. # subclass and benefit from the new behaviour here. This works because
  1027. # os.path.abspath('.') == os.getcwd().
  1028. return cls().absolute()
  1029. @classmethod
  1030. def home(cls):
  1031. """Return a new path pointing to the user's home directory (as
  1032. returned by os.path.expanduser('~')).
  1033. """
  1034. return cls("~").expanduser()
  1035. def absolute(self):
  1036. """Return an absolute version of this path by prepending the current
  1037. working directory. No normalization or symlink resolution is performed.
  1038. Use resolve() to get the canonical path to a file.
  1039. """
  1040. if self.is_absolute():
  1041. return self
  1042. elif self.drive:
  1043. # There is a CWD on each drive-letter drive.
  1044. cwd = self._flavour.abspath(self.drive)
  1045. else:
  1046. cwd = os.getcwd()
  1047. # Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
  1048. # We pass only one argument to with_segments() to avoid the cost
  1049. # of joining, and we exploit the fact that getcwd() returns a
  1050. # fully-normalized string by storing it in _str. This is used to
  1051. # implement Path.cwd().
  1052. if not self.root and not self._tail:
  1053. result = self.with_segments(cwd)
  1054. result._str = cwd
  1055. return result
  1056. return self.with_segments(cwd, self)
  1057. def resolve(self, strict=False):
  1058. """
  1059. Make the path absolute, resolving all symlinks on the way and also
  1060. normalizing it.
  1061. """
  1062. def check_eloop(e):
  1063. winerror = getattr(e, 'winerror', 0)
  1064. if e.errno == ELOOP or winerror == _WINERROR_CANT_RESOLVE_FILENAME:
  1065. raise RuntimeError("Symlink loop from %r" % e.filename)
  1066. try:
  1067. s = self._flavour.realpath(self, strict=strict)
  1068. except OSError as e:
  1069. check_eloop(e)
  1070. raise
  1071. p = self.with_segments(s)
  1072. # In non-strict mode, realpath() doesn't raise on symlink loops.
  1073. # Ensure we get an exception by calling stat()
  1074. if not strict:
  1075. try:
  1076. p.stat()
  1077. except OSError as e:
  1078. check_eloop(e)
  1079. return p
  1080. def owner(self):
  1081. """
  1082. Return the login name of the file owner.
  1083. """
  1084. try:
  1085. import pwd
  1086. return pwd.getpwuid(self.stat().st_uid).pw_name
  1087. except ImportError:
  1088. raise NotImplementedError("Path.owner() is unsupported on this system")
  1089. def group(self):
  1090. """
  1091. Return the group name of the file gid.
  1092. """
  1093. try:
  1094. import grp
  1095. return grp.getgrgid(self.stat().st_gid).gr_name
  1096. except ImportError:
  1097. raise NotImplementedError("Path.group() is unsupported on this system")
  1098. def readlink(self):
  1099. """
  1100. Return the path to which the symbolic link points.
  1101. """
  1102. if not hasattr(os, "readlink"):
  1103. raise NotImplementedError("os.readlink() not available on this system")
  1104. return self.with_segments(os.readlink(self))
  1105. def touch(self, mode=0o666, exist_ok=True):
  1106. """
  1107. Create this file with the given access mode, if it doesn't exist.
  1108. """
  1109. if exist_ok:
  1110. # First try to bump modification time
  1111. # Implementation note: GNU touch uses the UTIME_NOW option of
  1112. # the utimensat() / futimens() functions.
  1113. try:
  1114. os.utime(self, None)
  1115. except OSError:
  1116. # Avoid exception chaining
  1117. pass
  1118. else:
  1119. return
  1120. flags = os.O_CREAT | os.O_WRONLY
  1121. if not exist_ok:
  1122. flags |= os.O_EXCL
  1123. fd = os.open(self, flags, mode)
  1124. os.close(fd)
  1125. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  1126. """
  1127. Create a new directory at this given path.
  1128. """
  1129. try:
  1130. os.mkdir(self, mode)
  1131. except FileNotFoundError:
  1132. if not parents or self.parent == self:
  1133. raise
  1134. self.parent.mkdir(parents=True, exist_ok=True)
  1135. self.mkdir(mode, parents=False, exist_ok=exist_ok)
  1136. except OSError:
  1137. # Cannot rely on checking for EEXIST, since the operating system
  1138. # could give priority to other errors like EACCES or EROFS
  1139. if not exist_ok or not self.is_dir():
  1140. raise
  1141. def chmod(self, mode, *, follow_symlinks=True):
  1142. """
  1143. Change the permissions of the path, like os.chmod().
  1144. """
  1145. os.chmod(self, mode, follow_symlinks=follow_symlinks)
  1146. def lchmod(self, mode):
  1147. """
  1148. Like chmod(), except if the path points to a symlink, the symlink's
  1149. permissions are changed, rather than its target's.
  1150. """
  1151. self.chmod(mode, follow_symlinks=False)
  1152. def unlink(self, missing_ok=False):
  1153. """
  1154. Remove this file or link.
  1155. If the path is a directory, use rmdir() instead.
  1156. """
  1157. try:
  1158. os.unlink(self)
  1159. except FileNotFoundError:
  1160. if not missing_ok:
  1161. raise
  1162. def rmdir(self):
  1163. """
  1164. Remove this directory. The directory must be empty.
  1165. """
  1166. os.rmdir(self)
  1167. def rename(self, target):
  1168. """
  1169. Rename this path to the target path.
  1170. The target path may be absolute or relative. Relative paths are
  1171. interpreted relative to the current working directory, *not* the
  1172. directory of the Path object.
  1173. Returns the new Path instance pointing to the target path.
  1174. """
  1175. os.rename(self, target)
  1176. return self.with_segments(target)
  1177. def replace(self, target):
  1178. """
  1179. Rename this path to the target path, overwriting if that path exists.
  1180. The target path may be absolute or relative. Relative paths are
  1181. interpreted relative to the current working directory, *not* the
  1182. directory of the Path object.
  1183. Returns the new Path instance pointing to the target path.
  1184. """
  1185. os.replace(self, target)
  1186. return self.with_segments(target)
  1187. def symlink_to(self, target, target_is_directory=False):
  1188. """
  1189. Make this path a symlink pointing to the target path.
  1190. Note the order of arguments (link, target) is the reverse of os.symlink.
  1191. """
  1192. if not hasattr(os, "symlink"):
  1193. raise NotImplementedError("os.symlink() not available on this system")
  1194. os.symlink(target, self, target_is_directory)
  1195. def hardlink_to(self, target):
  1196. """
  1197. Make this path a hard link pointing to the same file as *target*.
  1198. Note the order of arguments (self, target) is the reverse of os.link's.
  1199. """
  1200. if not hasattr(os, "link"):
  1201. raise NotImplementedError("os.link() not available on this system")
  1202. os.link(target, self)
  1203. def expanduser(self):
  1204. """ Return a new path with expanded ~ and ~user constructs
  1205. (as returned by os.path.expanduser)
  1206. """
  1207. if (not (self.drive or self.root) and
  1208. self._tail and self._tail[0][:1] == '~'):
  1209. homedir = self._flavour.expanduser(self._tail[0])
  1210. if homedir[:1] == "~":
  1211. raise RuntimeError("Could not determine home directory.")
  1212. drv, root, tail = self._parse_path(homedir)
  1213. return self._from_parsed_parts(drv, root, tail + self._tail[1:])
  1214. return self
  1215. class PosixPath(Path, PurePosixPath):
  1216. """Path subclass for non-Windows systems.
  1217. On a POSIX system, instantiating a Path should return this object.
  1218. """
  1219. __slots__ = ()
  1220. if os.name == 'nt':
  1221. def __new__(cls, *args, **kwargs):
  1222. raise NotImplementedError(
  1223. f"cannot instantiate {cls.__name__!r} on your system")
  1224. class WindowsPath(Path, PureWindowsPath):
  1225. """Path subclass for Windows systems.
  1226. On a Windows system, instantiating a Path should return this object.
  1227. """
  1228. __slots__ = ()
  1229. if os.name != 'nt':
  1230. def __new__(cls, *args, **kwargs):
  1231. raise NotImplementedError(
  1232. f"cannot instantiate {cls.__name__!r} on your system")