pathlib.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  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. if not name or f.sep in name or (f.altsep and f.altsep in name) or name == '.':
  534. raise ValueError("Invalid name %r" % (name))
  535. return self._from_parsed_parts(self.drive, self.root,
  536. self._tail[:-1] + [name])
  537. def with_stem(self, stem):
  538. """Return a new path with the stem changed."""
  539. return self.with_name(stem + self.suffix)
  540. def with_suffix(self, suffix):
  541. """Return a new path with the file suffix changed. If the path
  542. has no suffix, add given suffix. If the given suffix is an empty
  543. string, remove the suffix from the path.
  544. """
  545. f = self._flavour
  546. if f.sep in suffix or f.altsep and f.altsep in suffix:
  547. raise ValueError("Invalid suffix %r" % (suffix,))
  548. if suffix and not suffix.startswith('.') or suffix == '.':
  549. raise ValueError("Invalid suffix %r" % (suffix))
  550. name = self.name
  551. if not name:
  552. raise ValueError("%r has an empty name" % (self,))
  553. old_suffix = self.suffix
  554. if not old_suffix:
  555. name = name + suffix
  556. else:
  557. name = name[:-len(old_suffix)] + suffix
  558. return self._from_parsed_parts(self.drive, self.root,
  559. self._tail[:-1] + [name])
  560. def relative_to(self, other, /, *_deprecated, walk_up=False):
  561. """Return the relative path to another path identified by the passed
  562. arguments. If the operation is not possible (because this is not
  563. related to the other path), raise ValueError.
  564. The *walk_up* parameter controls whether `..` may be used to resolve
  565. the path.
  566. """
  567. if _deprecated:
  568. msg = ("support for supplying more than one positional argument "
  569. "to pathlib.PurePath.relative_to() is deprecated and "
  570. "scheduled for removal in Python {remove}")
  571. warnings._deprecated("pathlib.PurePath.relative_to(*args)", msg,
  572. remove=(3, 14))
  573. other = self.with_segments(other, *_deprecated)
  574. for step, path in enumerate([other] + list(other.parents)):
  575. if self.is_relative_to(path):
  576. break
  577. elif not walk_up:
  578. raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
  579. elif path.name == '..':
  580. raise ValueError(f"'..' segment in {str(other)!r} cannot be walked")
  581. else:
  582. raise ValueError(f"{str(self)!r} and {str(other)!r} have different anchors")
  583. parts = ['..'] * step + self._tail[len(path._tail):]
  584. return self.with_segments(*parts)
  585. def is_relative_to(self, other, /, *_deprecated):
  586. """Return True if the path is relative to another path or False.
  587. """
  588. if _deprecated:
  589. msg = ("support for supplying more than one argument to "
  590. "pathlib.PurePath.is_relative_to() is deprecated and "
  591. "scheduled for removal in Python {remove}")
  592. warnings._deprecated("pathlib.PurePath.is_relative_to(*args)",
  593. msg, remove=(3, 14))
  594. other = self.with_segments(other, *_deprecated)
  595. return other == self or other in self.parents
  596. @property
  597. def parts(self):
  598. """An object providing sequence-like access to the
  599. components in the filesystem path."""
  600. if self.drive or self.root:
  601. return (self.drive + self.root,) + tuple(self._tail)
  602. else:
  603. return tuple(self._tail)
  604. def joinpath(self, *pathsegments):
  605. """Combine this path with one or several arguments, and return a
  606. new path representing either a subpath (if all arguments are relative
  607. paths) or a totally different path (if one of the arguments is
  608. anchored).
  609. """
  610. return self.with_segments(self, *pathsegments)
  611. def __truediv__(self, key):
  612. try:
  613. return self.joinpath(key)
  614. except TypeError:
  615. return NotImplemented
  616. def __rtruediv__(self, key):
  617. try:
  618. return self.with_segments(key, self)
  619. except TypeError:
  620. return NotImplemented
  621. @property
  622. def parent(self):
  623. """The logical parent of the path."""
  624. drv = self.drive
  625. root = self.root
  626. tail = self._tail
  627. if not tail:
  628. return self
  629. return self._from_parsed_parts(drv, root, tail[:-1])
  630. @property
  631. def parents(self):
  632. """A sequence of this path's logical parents."""
  633. # The value of this property should not be cached on the path object,
  634. # as doing so would introduce a reference cycle.
  635. return _PathParents(self)
  636. def is_absolute(self):
  637. """True if the path is absolute (has both a root and, if applicable,
  638. a drive)."""
  639. if self._flavour is ntpath:
  640. # ntpath.isabs() is defective - see GH-44626.
  641. return bool(self.drive and self.root)
  642. elif self._flavour is posixpath:
  643. # Optimization: work with raw paths on POSIX.
  644. for path in self._raw_paths:
  645. if path.startswith('/'):
  646. return True
  647. return False
  648. else:
  649. return self._flavour.isabs(str(self))
  650. def is_reserved(self):
  651. """Return True if the path contains one of the special names reserved
  652. by the system, if any."""
  653. if self._flavour is posixpath or not self._tail:
  654. return False
  655. # NOTE: the rules for reserved names seem somewhat complicated
  656. # (e.g. r"..\NUL" is reserved but not r"foo\NUL" if "foo" does not
  657. # exist). We err on the side of caution and return True for paths
  658. # which are not considered reserved by Windows.
  659. if self.drive.startswith('\\\\'):
  660. # UNC paths are never reserved.
  661. return False
  662. name = self._tail[-1].partition('.')[0].partition(':')[0].rstrip(' ')
  663. return name.upper() in _WIN_RESERVED_NAMES
  664. def match(self, path_pattern, *, case_sensitive=None):
  665. """
  666. Return True if this path matches the given pattern.
  667. """
  668. if not isinstance(path_pattern, PurePath):
  669. path_pattern = self.with_segments(path_pattern)
  670. if case_sensitive is None:
  671. case_sensitive = _is_case_sensitive(self._flavour)
  672. pattern = _compile_pattern_lines(path_pattern._lines, case_sensitive)
  673. if path_pattern.drive or path_pattern.root:
  674. return pattern.match(self._lines) is not None
  675. elif path_pattern._tail:
  676. return pattern.search(self._lines) is not None
  677. else:
  678. raise ValueError("empty pattern")
  679. # Can't subclass os.PathLike from PurePath and keep the constructor
  680. # optimizations in PurePath.__slots__.
  681. os.PathLike.register(PurePath)
  682. class PurePosixPath(PurePath):
  683. """PurePath subclass for non-Windows systems.
  684. On a POSIX system, instantiating a PurePath should return this object.
  685. However, you can also instantiate it directly on any system.
  686. """
  687. _flavour = posixpath
  688. __slots__ = ()
  689. class PureWindowsPath(PurePath):
  690. """PurePath subclass for Windows systems.
  691. On a Windows system, instantiating a PurePath should return this object.
  692. However, you can also instantiate it directly on any system.
  693. """
  694. _flavour = ntpath
  695. __slots__ = ()
  696. # Filesystem-accessing classes
  697. class Path(PurePath):
  698. """PurePath subclass that can make system calls.
  699. Path represents a filesystem path but unlike PurePath, also offers
  700. methods to do system calls on path objects. Depending on your system,
  701. instantiating a Path will return either a PosixPath or a WindowsPath
  702. object. You can also instantiate a PosixPath or WindowsPath directly,
  703. but cannot instantiate a WindowsPath on a POSIX system or vice versa.
  704. """
  705. __slots__ = ()
  706. def stat(self, *, follow_symlinks=True):
  707. """
  708. Return the result of the stat() system call on this path, like
  709. os.stat() does.
  710. """
  711. return os.stat(self, follow_symlinks=follow_symlinks)
  712. def lstat(self):
  713. """
  714. Like stat(), except if the path points to a symlink, the symlink's
  715. status information is returned, rather than its target's.
  716. """
  717. return self.stat(follow_symlinks=False)
  718. # Convenience functions for querying the stat results
  719. def exists(self, *, follow_symlinks=True):
  720. """
  721. Whether this path exists.
  722. This method normally follows symlinks; to check whether a symlink exists,
  723. add the argument follow_symlinks=False.
  724. """
  725. try:
  726. self.stat(follow_symlinks=follow_symlinks)
  727. except OSError as e:
  728. if not _ignore_error(e):
  729. raise
  730. return False
  731. except ValueError:
  732. # Non-encodable path
  733. return False
  734. return True
  735. def is_dir(self):
  736. """
  737. Whether this path is a directory.
  738. """
  739. try:
  740. return S_ISDIR(self.stat().st_mode)
  741. except OSError as e:
  742. if not _ignore_error(e):
  743. raise
  744. # Path doesn't exist or is a broken symlink
  745. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  746. return False
  747. except ValueError:
  748. # Non-encodable path
  749. return False
  750. def is_file(self):
  751. """
  752. Whether this path is a regular file (also True for symlinks pointing
  753. to regular files).
  754. """
  755. try:
  756. return S_ISREG(self.stat().st_mode)
  757. except OSError as e:
  758. if not _ignore_error(e):
  759. raise
  760. # Path doesn't exist or is a broken symlink
  761. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  762. return False
  763. except ValueError:
  764. # Non-encodable path
  765. return False
  766. def is_mount(self):
  767. """
  768. Check if this path is a mount point
  769. """
  770. return self._flavour.ismount(self)
  771. def is_symlink(self):
  772. """
  773. Whether this path is a symbolic link.
  774. """
  775. try:
  776. return S_ISLNK(self.lstat().st_mode)
  777. except OSError as e:
  778. if not _ignore_error(e):
  779. raise
  780. # Path doesn't exist
  781. return False
  782. except ValueError:
  783. # Non-encodable path
  784. return False
  785. def is_junction(self):
  786. """
  787. Whether this path is a junction.
  788. """
  789. return self._flavour.isjunction(self)
  790. def is_block_device(self):
  791. """
  792. Whether this path is a block device.
  793. """
  794. try:
  795. return S_ISBLK(self.stat().st_mode)
  796. except OSError as e:
  797. if not _ignore_error(e):
  798. raise
  799. # Path doesn't exist or is a broken symlink
  800. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  801. return False
  802. except ValueError:
  803. # Non-encodable path
  804. return False
  805. def is_char_device(self):
  806. """
  807. Whether this path is a character device.
  808. """
  809. try:
  810. return S_ISCHR(self.stat().st_mode)
  811. except OSError as e:
  812. if not _ignore_error(e):
  813. raise
  814. # Path doesn't exist or is a broken symlink
  815. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  816. return False
  817. except ValueError:
  818. # Non-encodable path
  819. return False
  820. def is_fifo(self):
  821. """
  822. Whether this path is a FIFO.
  823. """
  824. try:
  825. return S_ISFIFO(self.stat().st_mode)
  826. except OSError as e:
  827. if not _ignore_error(e):
  828. raise
  829. # Path doesn't exist or is a broken symlink
  830. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  831. return False
  832. except ValueError:
  833. # Non-encodable path
  834. return False
  835. def is_socket(self):
  836. """
  837. Whether this path is a socket.
  838. """
  839. try:
  840. return S_ISSOCK(self.stat().st_mode)
  841. except OSError as e:
  842. if not _ignore_error(e):
  843. raise
  844. # Path doesn't exist or is a broken symlink
  845. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  846. return False
  847. except ValueError:
  848. # Non-encodable path
  849. return False
  850. def samefile(self, other_path):
  851. """Return whether other_path is the same or not as this file
  852. (as returned by os.path.samefile()).
  853. """
  854. st = self.stat()
  855. try:
  856. other_st = other_path.stat()
  857. except AttributeError:
  858. other_st = self.with_segments(other_path).stat()
  859. return self._flavour.samestat(st, other_st)
  860. def open(self, mode='r', buffering=-1, encoding=None,
  861. errors=None, newline=None):
  862. """
  863. Open the file pointed to by this path and return a file object, as
  864. the built-in open() function does.
  865. """
  866. if "b" not in mode:
  867. encoding = io.text_encoding(encoding)
  868. return io.open(self, mode, buffering, encoding, errors, newline)
  869. def read_bytes(self):
  870. """
  871. Open the file in bytes mode, read it, and close the file.
  872. """
  873. with self.open(mode='rb') as f:
  874. return f.read()
  875. def read_text(self, encoding=None, errors=None):
  876. """
  877. Open the file in text mode, read it, and close the file.
  878. """
  879. encoding = io.text_encoding(encoding)
  880. with self.open(mode='r', encoding=encoding, errors=errors) as f:
  881. return f.read()
  882. def write_bytes(self, data):
  883. """
  884. Open the file in bytes mode, write to it, and close the file.
  885. """
  886. # type-check for the buffer interface before truncating the file
  887. view = memoryview(data)
  888. with self.open(mode='wb') as f:
  889. return f.write(view)
  890. def write_text(self, data, encoding=None, errors=None, newline=None):
  891. """
  892. Open the file in text mode, write to it, and close the file.
  893. """
  894. if not isinstance(data, str):
  895. raise TypeError('data must be str, not %s' %
  896. data.__class__.__name__)
  897. encoding = io.text_encoding(encoding)
  898. with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
  899. return f.write(data)
  900. def iterdir(self):
  901. """Yield path objects of the directory contents.
  902. The children are yielded in arbitrary order, and the
  903. special entries '.' and '..' are not included.
  904. """
  905. for name in os.listdir(self):
  906. yield self._make_child_relpath(name)
  907. def _scandir(self):
  908. # bpo-24132: a future version of pathlib will support subclassing of
  909. # pathlib.Path to customize how the filesystem is accessed. This
  910. # includes scandir(), which is used to implement glob().
  911. return os.scandir(self)
  912. def _make_child_relpath(self, name):
  913. path_str = str(self)
  914. tail = self._tail
  915. if tail:
  916. path_str = f'{path_str}{self._flavour.sep}{name}'
  917. elif path_str != '.':
  918. path_str = f'{path_str}{name}'
  919. else:
  920. path_str = name
  921. path = self.with_segments(path_str)
  922. path._str = path_str
  923. path._drv = self.drive
  924. path._root = self.root
  925. path._tail_cached = tail + [name]
  926. return path
  927. def glob(self, pattern, *, case_sensitive=None):
  928. """Iterate over this subtree and yield all existing files (of any
  929. kind, including directories) matching the given relative pattern.
  930. """
  931. sys.audit("pathlib.Path.glob", self, pattern)
  932. if not pattern:
  933. raise ValueError("Unacceptable pattern: {!r}".format(pattern))
  934. drv, root, pattern_parts = self._parse_path(pattern)
  935. if drv or root:
  936. raise NotImplementedError("Non-relative patterns are unsupported")
  937. if pattern[-1] in (self._flavour.sep, self._flavour.altsep):
  938. pattern_parts.append('')
  939. selector = _make_selector(tuple(pattern_parts), self._flavour, case_sensitive)
  940. for p in selector.select_from(self):
  941. yield p
  942. def rglob(self, pattern, *, case_sensitive=None):
  943. """Recursively yield all existing files (of any kind, including
  944. directories) matching the given relative pattern, anywhere in
  945. this subtree.
  946. """
  947. sys.audit("pathlib.Path.rglob", self, pattern)
  948. drv, root, pattern_parts = self._parse_path(pattern)
  949. if drv or root:
  950. raise NotImplementedError("Non-relative patterns are unsupported")
  951. if pattern and pattern[-1] in (self._flavour.sep, self._flavour.altsep):
  952. pattern_parts.append('')
  953. selector = _make_selector(("**",) + tuple(pattern_parts), self._flavour, case_sensitive)
  954. for p in selector.select_from(self):
  955. yield p
  956. def walk(self, top_down=True, on_error=None, follow_symlinks=False):
  957. """Walk the directory tree from this directory, similar to os.walk()."""
  958. sys.audit("pathlib.Path.walk", self, on_error, follow_symlinks)
  959. paths = [self]
  960. while paths:
  961. path = paths.pop()
  962. if isinstance(path, tuple):
  963. yield path
  964. continue
  965. # We may not have read permission for self, in which case we can't
  966. # get a list of the files the directory contains. os.walk()
  967. # always suppressed the exception in that instance, rather than
  968. # blow up for a minor reason when (say) a thousand readable
  969. # directories are still left to visit. That logic is copied here.
  970. try:
  971. scandir_it = path._scandir()
  972. except OSError as error:
  973. if on_error is not None:
  974. on_error(error)
  975. continue
  976. with scandir_it:
  977. dirnames = []
  978. filenames = []
  979. for entry in scandir_it:
  980. try:
  981. is_dir = entry.is_dir(follow_symlinks=follow_symlinks)
  982. except OSError:
  983. # Carried over from os.path.isdir().
  984. is_dir = False
  985. if is_dir:
  986. dirnames.append(entry.name)
  987. else:
  988. filenames.append(entry.name)
  989. if top_down:
  990. yield path, dirnames, filenames
  991. else:
  992. paths.append((path, dirnames, filenames))
  993. paths += [path._make_child_relpath(d) for d in reversed(dirnames)]
  994. def __init__(self, *args, **kwargs):
  995. if kwargs:
  996. msg = ("support for supplying keyword arguments to pathlib.PurePath "
  997. "is deprecated and scheduled for removal in Python {remove}")
  998. warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
  999. super().__init__(*args)
  1000. def __new__(cls, *args, **kwargs):
  1001. if cls is Path:
  1002. cls = WindowsPath if os.name == 'nt' else PosixPath
  1003. return object.__new__(cls)
  1004. def __enter__(self):
  1005. # In previous versions of pathlib, __exit__() marked this path as
  1006. # closed; subsequent attempts to perform I/O would raise an IOError.
  1007. # This functionality was never documented, and had the effect of
  1008. # making Path objects mutable, contrary to PEP 428.
  1009. # In Python 3.9 __exit__() was made a no-op.
  1010. # In Python 3.11 __enter__() began emitting DeprecationWarning.
  1011. # In Python 3.13 __enter__() and __exit__() should be removed.
  1012. warnings.warn("pathlib.Path.__enter__() is deprecated and scheduled "
  1013. "for removal in Python 3.13; Path objects as a context "
  1014. "manager is a no-op",
  1015. DeprecationWarning, stacklevel=2)
  1016. return self
  1017. def __exit__(self, t, v, tb):
  1018. pass
  1019. # Public API
  1020. @classmethod
  1021. def cwd(cls):
  1022. """Return a new path pointing to the current working directory."""
  1023. # We call 'absolute()' rather than using 'os.getcwd()' directly to
  1024. # enable users to replace the implementation of 'absolute()' in a
  1025. # subclass and benefit from the new behaviour here. This works because
  1026. # os.path.abspath('.') == os.getcwd().
  1027. return cls().absolute()
  1028. @classmethod
  1029. def home(cls):
  1030. """Return a new path pointing to the user's home directory (as
  1031. returned by os.path.expanduser('~')).
  1032. """
  1033. return cls("~").expanduser()
  1034. def absolute(self):
  1035. """Return an absolute version of this path by prepending the current
  1036. working directory. No normalization or symlink resolution is performed.
  1037. Use resolve() to get the canonical path to a file.
  1038. """
  1039. if self.is_absolute():
  1040. return self
  1041. elif self.drive:
  1042. # There is a CWD on each drive-letter drive.
  1043. cwd = self._flavour.abspath(self.drive)
  1044. else:
  1045. cwd = os.getcwd()
  1046. # Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
  1047. # We pass only one argument to with_segments() to avoid the cost
  1048. # of joining, and we exploit the fact that getcwd() returns a
  1049. # fully-normalized string by storing it in _str. This is used to
  1050. # implement Path.cwd().
  1051. if not self.root and not self._tail:
  1052. result = self.with_segments(cwd)
  1053. result._str = cwd
  1054. return result
  1055. return self.with_segments(cwd, self)
  1056. def resolve(self, strict=False):
  1057. """
  1058. Make the path absolute, resolving all symlinks on the way and also
  1059. normalizing it.
  1060. """
  1061. def check_eloop(e):
  1062. winerror = getattr(e, 'winerror', 0)
  1063. if e.errno == ELOOP or winerror == _WINERROR_CANT_RESOLVE_FILENAME:
  1064. raise RuntimeError("Symlink loop from %r" % e.filename)
  1065. try:
  1066. s = self._flavour.realpath(self, strict=strict)
  1067. except OSError as e:
  1068. check_eloop(e)
  1069. raise
  1070. p = self.with_segments(s)
  1071. # In non-strict mode, realpath() doesn't raise on symlink loops.
  1072. # Ensure we get an exception by calling stat()
  1073. if not strict:
  1074. try:
  1075. p.stat()
  1076. except OSError as e:
  1077. check_eloop(e)
  1078. return p
  1079. def owner(self):
  1080. """
  1081. Return the login name of the file owner.
  1082. """
  1083. try:
  1084. import pwd
  1085. return pwd.getpwuid(self.stat().st_uid).pw_name
  1086. except ImportError:
  1087. raise NotImplementedError("Path.owner() is unsupported on this system")
  1088. def group(self):
  1089. """
  1090. Return the group name of the file gid.
  1091. """
  1092. try:
  1093. import grp
  1094. return grp.getgrgid(self.stat().st_gid).gr_name
  1095. except ImportError:
  1096. raise NotImplementedError("Path.group() is unsupported on this system")
  1097. def readlink(self):
  1098. """
  1099. Return the path to which the symbolic link points.
  1100. """
  1101. if not hasattr(os, "readlink"):
  1102. raise NotImplementedError("os.readlink() not available on this system")
  1103. return self.with_segments(os.readlink(self))
  1104. def touch(self, mode=0o666, exist_ok=True):
  1105. """
  1106. Create this file with the given access mode, if it doesn't exist.
  1107. """
  1108. if exist_ok:
  1109. # First try to bump modification time
  1110. # Implementation note: GNU touch uses the UTIME_NOW option of
  1111. # the utimensat() / futimens() functions.
  1112. try:
  1113. os.utime(self, None)
  1114. except OSError:
  1115. # Avoid exception chaining
  1116. pass
  1117. else:
  1118. return
  1119. flags = os.O_CREAT | os.O_WRONLY
  1120. if not exist_ok:
  1121. flags |= os.O_EXCL
  1122. fd = os.open(self, flags, mode)
  1123. os.close(fd)
  1124. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  1125. """
  1126. Create a new directory at this given path.
  1127. """
  1128. try:
  1129. os.mkdir(self, mode)
  1130. except FileNotFoundError:
  1131. if not parents or self.parent == self:
  1132. raise
  1133. self.parent.mkdir(parents=True, exist_ok=True)
  1134. self.mkdir(mode, parents=False, exist_ok=exist_ok)
  1135. except OSError:
  1136. # Cannot rely on checking for EEXIST, since the operating system
  1137. # could give priority to other errors like EACCES or EROFS
  1138. if not exist_ok or not self.is_dir():
  1139. raise
  1140. def chmod(self, mode, *, follow_symlinks=True):
  1141. """
  1142. Change the permissions of the path, like os.chmod().
  1143. """
  1144. os.chmod(self, mode, follow_symlinks=follow_symlinks)
  1145. def lchmod(self, mode):
  1146. """
  1147. Like chmod(), except if the path points to a symlink, the symlink's
  1148. permissions are changed, rather than its target's.
  1149. """
  1150. self.chmod(mode, follow_symlinks=False)
  1151. def unlink(self, missing_ok=False):
  1152. """
  1153. Remove this file or link.
  1154. If the path is a directory, use rmdir() instead.
  1155. """
  1156. try:
  1157. os.unlink(self)
  1158. except FileNotFoundError:
  1159. if not missing_ok:
  1160. raise
  1161. def rmdir(self):
  1162. """
  1163. Remove this directory. The directory must be empty.
  1164. """
  1165. os.rmdir(self)
  1166. def rename(self, target):
  1167. """
  1168. Rename this path to the target path.
  1169. The target path may be absolute or relative. Relative paths are
  1170. interpreted relative to the current working directory, *not* the
  1171. directory of the Path object.
  1172. Returns the new Path instance pointing to the target path.
  1173. """
  1174. os.rename(self, target)
  1175. return self.with_segments(target)
  1176. def replace(self, target):
  1177. """
  1178. Rename this path to the target path, overwriting if that path exists.
  1179. The target path may be absolute or relative. Relative paths are
  1180. interpreted relative to the current working directory, *not* the
  1181. directory of the Path object.
  1182. Returns the new Path instance pointing to the target path.
  1183. """
  1184. os.replace(self, target)
  1185. return self.with_segments(target)
  1186. def symlink_to(self, target, target_is_directory=False):
  1187. """
  1188. Make this path a symlink pointing to the target path.
  1189. Note the order of arguments (link, target) is the reverse of os.symlink.
  1190. """
  1191. if not hasattr(os, "symlink"):
  1192. raise NotImplementedError("os.symlink() not available on this system")
  1193. os.symlink(target, self, target_is_directory)
  1194. def hardlink_to(self, target):
  1195. """
  1196. Make this path a hard link pointing to the same file as *target*.
  1197. Note the order of arguments (self, target) is the reverse of os.link's.
  1198. """
  1199. if not hasattr(os, "link"):
  1200. raise NotImplementedError("os.link() not available on this system")
  1201. os.link(target, self)
  1202. def expanduser(self):
  1203. """ Return a new path with expanded ~ and ~user constructs
  1204. (as returned by os.path.expanduser)
  1205. """
  1206. if (not (self.drive or self.root) and
  1207. self._tail and self._tail[0][:1] == '~'):
  1208. homedir = self._flavour.expanduser(self._tail[0])
  1209. if homedir[:1] == "~":
  1210. raise RuntimeError("Could not determine home directory.")
  1211. drv, root, tail = self._parse_path(homedir)
  1212. return self._from_parsed_parts(drv, root, tail + self._tail[1:])
  1213. return self
  1214. class PosixPath(Path, PurePosixPath):
  1215. """Path subclass for non-Windows systems.
  1216. On a POSIX system, instantiating a Path should return this object.
  1217. """
  1218. __slots__ = ()
  1219. if os.name == 'nt':
  1220. def __new__(cls, *args, **kwargs):
  1221. raise NotImplementedError(
  1222. f"cannot instantiate {cls.__name__!r} on your system")
  1223. class WindowsPath(Path, PureWindowsPath):
  1224. """Path subclass for Windows systems.
  1225. On a Windows system, instantiating a Path should return this object.
  1226. """
  1227. __slots__ = ()
  1228. if os.name != 'nt':
  1229. def __new__(cls, *args, **kwargs):
  1230. raise NotImplementedError(
  1231. f"cannot instantiate {cls.__name__!r} on your system")