Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.2k
Expand file tree
/
Copy pathpathlib.py
More file actions
Latest commit
1406 lines (1209 loc) · 47.4 KB
/
Copy pathpathlib.py
File metadata and controls
1406 lines (1209 loc) · 47.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
importfnmatch
importfunctools
importio
importntpath
importos
importposixpath
importre
importsys
importwarnings
from_collections_abcimportSequence
fromerrnoimportENOENT, ENOTDIR, EBADF, ELOOP
fromoperatorimportattrgetter
fromstatimportS_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO
fromurllib.parseimportquote_from_bytesasurlquote_from_bytes
__all__= [
"PurePath", "PurePosixPath", "PureWindowsPath",
"Path", "PosixPath", "WindowsPath",
]
#
# Internals
#
_WINERROR_NOT_READY=21# drive exists but is not accessible
_WINERROR_INVALID_NAME=123# fix for bpo-35306
_WINERROR_CANT_RESOLVE_FILENAME=1921# broken symlink pointing to itself
# EBADF - guard against macOS `stat` throwing EBADF
_IGNORED_ERRNOS= (ENOENT, ENOTDIR, EBADF, ELOOP)
_IGNORED_WINERRORS= (
_WINERROR_NOT_READY,
_WINERROR_INVALID_NAME,
_WINERROR_CANT_RESOLVE_FILENAME)
def_ignore_error(exception):
return (getattr(exception, 'errno', None) in_IGNORED_ERRNOSor
getattr(exception, 'winerror', None) in_IGNORED_WINERRORS)
def_is_wildcard_pattern(pat):
# Whether this pattern needs actual matching using fnmatch, or can
# be looked up directly as a file.
return"*"inpator"?"inpator"["inpat
class_Flavour(object):
"""A flavour implements a particular (platform-specific) set of path
semantics."""
def__init__(self):
self.join=self.sep.join
defparse_parts(self, parts):
parsed= []
sep=self.sep
altsep=self.altsep
drv=root=''
it=reversed(parts)
forpartinit:
ifnotpart:
continue
ifaltsep:
part=part.replace(altsep, sep)
drv, root, rel=self.splitroot(part)
ifsepinrel:
forxinreversed(rel.split(sep)):
ifxandx!='.':
parsed.append(sys.intern(x))
else:
ifrelandrel!='.':
parsed.append(sys.intern(rel))
ifdrvorroot:
ifnotdrv:
# If no drive is present, try to find one in the previous
# parts. This makes the result of parsing e.g.
# ("C:", "/", "a") reasonably intuitive.
forpartinit:
ifnotpart:
continue
ifaltsep:
part=part.replace(altsep, sep)
drv=self.splitroot(part)[0]
ifdrv:
break
break
ifdrvorroot:
parsed.append(drv+root)
parsed.reverse()
returndrv, root, parsed
defjoin_parsed_parts(self, drv, root, parts, drv2, root2, parts2):
"""
Join the two paths represented by the respective
(drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
"""
ifroot2:
ifnotdrv2anddrv:
returndrv, root2, [drv+root2] +parts2[1:]
elifdrv2:
ifdrv2==drvorself.casefold(drv2) ==self.casefold(drv):
# Same drive => second path is relative to the first
returndrv, root, parts+parts2[1:]
else:
# Second path is non-anchored (common case)
returndrv, root, parts+parts2
returndrv2, root2, parts2
class_WindowsFlavour(_Flavour):
# Reference for Windows paths can be found at
# http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
sep='\\'
altsep='/'
has_drv=True
pathmod=ntpath
is_supported= (os.name=='nt')
drive_letters=set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
ext_namespace_prefix='\\\\?\\'
reserved_names= (
{'CON', 'PRN', 'AUX', 'NUL', 'CONIN$', 'CONOUT$'} |
{'COM%s'%cforcin'123456789\xb9\xb2\xb3'} |
{'LPT%s'%cforcin'123456789\xb9\xb2\xb3'}
)
# Interesting findings about extended paths:
# * '\\?\c:\a' is an extended path, which bypasses normal Windows API
# path processing. Thus relative paths are not resolved and slash is not
# translated to backslash. It has the native NT path limit of 32767
# characters, but a bit less after resolving device symbolic links,
# such as '\??\C:' => '\Device\HarddiskVolume2'.
# * '\\?\c:/a' looks for a device named 'C:/a' because slash is a
# regular name character in the object namespace.
# * '\\?\c:\foo/bar' is invalid because '/' is illegal in NT filesystems.
# The only path separator at the filesystem level is backslash.
# * '//?/c:\a' and '//?/c:/a' are effectively equivalent to '\\.\c:\a' and
# thus limited to MAX_PATH.
# * Prior to Windows 8, ANSI API bytes paths are limited to MAX_PATH,
# even with the '\\?\' prefix.
defsplitroot(self, part, sep=sep):
first=part[0:1]
second=part[1:2]
if (second==sepandfirst==sep):
# XXX extended paths should also disable the collapsing of "."
# components (according to MSDN docs).
prefix, part=self._split_extended_path(part)
first=part[0:1]
second=part[1:2]
else:
prefix=''
third=part[2:3]
if (second==sepandfirst==sepandthird!=sep):
# is a UNC path:
# vvvvvvvvvvvvvvvvvvvvv root
# \\machine\mountpoint\directory\etc\...
# directory ^^^^^^^^^^^^^^
index=part.find(sep, 2)
ifindex!=-1:
index2=part.find(sep, index+1)
# a UNC path can't have two slashes in a row
# (after the initial two)
ifindex2!=index+1:
ifindex2==-1:
index2=len(part)
ifprefix:
returnprefix+part[1:index2], sep, part[index2+1:]
else:
returnpart[:index2], sep, part[index2+1:]
drv=root=''
ifsecond==':'andfirstinself.drive_letters:
drv=part[:2]
part=part[2:]
first=third
iffirst==sep:
root=first
part=part.lstrip(sep)
returnprefix+drv, root, part
defcasefold(self, s):
returns.lower()
defcasefold_parts(self, parts):
return [p.lower() forpinparts]
defcompile_pattern(self, pattern):
returnre.compile(fnmatch.translate(pattern), re.IGNORECASE).fullmatch
def_split_extended_path(self, s, ext_prefix=ext_namespace_prefix):
prefix=''
ifs.startswith(ext_prefix):
prefix=s[:4]
s=s[4:]
ifs.startswith('UNC\\'):
prefix+=s[:3]
s='\\'+s[3:]
returnprefix, s
defis_reserved(self, parts):
# NOTE: the rules for reserved names seem somewhat complicated
# (e.g. r"..\NUL" is reserved but not r"foo\NUL" if "foo" does not
# exist). We err on the side of caution and return True for paths
# which are not considered reserved by Windows.
ifnotparts:
returnFalse
ifparts[0].startswith('\\\\'):
# UNC paths are never reserved
returnFalse
name=parts[-1].partition('.')[0].partition(':')[0].rstrip(' ')
returnname.upper() inself.reserved_names
defmake_uri(self, path):
# Under Windows, file URIs use the UTF-8 encoding.
drive=path.drive
iflen(drive) ==2anddrive[1] ==':':
# It's a path on a local drive => 'file:///c:/a/b'
rest=path.as_posix()[2:].lstrip('/')
return'file:///%s/%s'% (
drive, urlquote_from_bytes(rest.encode('utf-8')))
else:
# It's a path on a network drive => 'file://host/share/a/b'
return'file:'+urlquote_from_bytes(path.as_posix().encode('utf-8'))
class_PosixFlavour(_Flavour):
sep='/'
altsep=''
has_drv=False
pathmod=posixpath
is_supported= (os.name!='nt')
defsplitroot(self, part, sep=sep):
ifpartandpart[0] ==sep:
stripped_part=part.lstrip(sep)
# According to POSIX path resolution:
# http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11
# "A pathname that begins with two successive slashes may be
# interpreted in an implementation-defined manner, although more
# than two leading slashes shall be treated as a single slash".
iflen(part) -len(stripped_part) ==2:
return'', sep*2, stripped_part
else:
return'', sep, stripped_part
else:
return'', '', part
defcasefold(self, s):
returns
defcasefold_parts(self, parts):
returnparts
defcompile_pattern(self, pattern):
returnre.compile(fnmatch.translate(pattern)).fullmatch
defis_reserved(self, parts):
returnFalse
defmake_uri(self, path):
# We represent the path using the local filesystem encoding,
# for portability to other applications.
bpath=bytes(path)
return'file://'+urlquote_from_bytes(bpath)
_windows_flavour=_WindowsFlavour()
_posix_flavour=_PosixFlavour()
#
# Globbing helpers
#
def_make_selector(pattern_parts, flavour):
pat=pattern_parts[0]
child_parts=pattern_parts[1:]
ifnotpat:
return_TerminatingSelector()
ifpat=='**':
cls=_RecursiveWildcardSelector
elif'**'inpat:
raiseValueError("Invalid pattern: '**' can only be an entire path component")
elif_is_wildcard_pattern(pat):
cls=_WildcardSelector
else:
cls=_PreciseSelector
returncls(pat, child_parts, flavour)
ifhasattr(functools, "lru_cache"):
_make_selector=functools.lru_cache()(_make_selector)
class_Selector:
"""A selector matches a specific glob pattern part against the children
of a given path."""
def__init__(self, child_parts, flavour):
self.child_parts=child_parts
ifchild_parts:
self.successor=_make_selector(child_parts, flavour)
self.dironly=True
else:
self.successor=_TerminatingSelector()
self.dironly=False
defselect_from(self, parent_path):
"""Iterate over all child paths of `parent_path` matched by this
selector. This can contain parent_path itself."""
path_cls=type(parent_path)
is_dir=path_cls.is_dir
exists=path_cls.exists
scandir=path_cls._scandir
ifnotis_dir(parent_path):
returniter([])
returnself._select_from(parent_path, is_dir, exists, scandir)
class_TerminatingSelector:
def_select_from(self, parent_path, is_dir, exists, scandir):
yieldparent_path
class_PreciseSelector(_Selector):
def__init__(self, name, child_parts, flavour):
self.name=name
_Selector.__init__(self, child_parts, flavour)
def_select_from(self, parent_path, is_dir, exists, scandir):
try:
path=parent_path._make_child_relpath(self.name)
if (is_dirifself.dironlyelseexists)(path):
forpinself.successor._select_from(path, is_dir, exists, scandir):
yieldp
exceptPermissionError:
return
class_WildcardSelector(_Selector):
def__init__(self, pat, child_parts, flavour):
self.match=flavour.compile_pattern(pat)
_Selector.__init__(self, child_parts, flavour)
def_select_from(self, parent_path, is_dir, exists, scandir):
try:
withscandir(parent_path) asscandir_it:
entries=list(scandir_it)
forentryinentries:
ifself.dironly:
try:
# "entry.is_dir()" can raise PermissionError
# in some cases (see bpo-38894), which is not
# among the errors ignored by _ignore_error()
ifnotentry.is_dir():
continue
exceptOSErrorase:
ifnot_ignore_error(e):
raise
continue
name=entry.name
ifself.match(name):
path=parent_path._make_child_relpath(name)
forpinself.successor._select_from(path, is_dir, exists, scandir):
yieldp
exceptPermissionError:
return
class_RecursiveWildcardSelector(_Selector):
def__init__(self, pat, child_parts, flavour):
_Selector.__init__(self, child_parts, flavour)
def_iterate_directories(self, parent_path, is_dir, scandir):
yieldparent_path
try:
withscandir(parent_path) asscandir_it:
entries=list(scandir_it)
forentryinentries:
entry_is_dir=False
try:
entry_is_dir=entry.is_dir(follow_symlinks=False)
exceptOSErrorase:
ifnot_ignore_error(e):
raise
ifentry_is_dir:
path=parent_path._make_child_relpath(entry.name)
forpinself._iterate_directories(path, is_dir, scandir):
yieldp
exceptPermissionError:
return
def_select_from(self, parent_path, is_dir, exists, scandir):
try:
yielded=set()
try:
successor_select=self.successor._select_from
forstarting_pointinself._iterate_directories(parent_path, is_dir, scandir):
forpinsuccessor_select(starting_point, is_dir, exists, scandir):
ifpnotinyielded:
yieldp
yielded.add(p)
finally:
yielded.clear()
exceptPermissionError:
return
#
# Public API
#
class_PathParents(Sequence):
"""This object provides sequence-like access to the logical ancestors
of a path. Don't try to construct it yourself."""
__slots__= ('_pathcls', '_drv', '_root', '_parts')
def__init__(self, path):
# We don't store the instance to avoid reference cycles
self._pathcls=type(path)
self._drv=path._drv
self._root=path._root
self._parts=path._parts
def__len__(self):
ifself._drvorself._root:
returnlen(self._parts) -1
else:
returnlen(self._parts)
def__getitem__(self, idx):
ifisinstance(idx, slice):
returntuple(self[i] foriinrange(*idx.indices(len(self))))
ifidx>=len(self) oridx<-len(self):
raiseIndexError(idx)
ifidx<0:
idx+=len(self)
returnself._pathcls._from_parsed_parts(self._drv, self._root,
self._parts[:-idx-1])
def__repr__(self):
return"<{}.parents>".format(self._pathcls.__name__)
classPurePath(object):
"""Base class for manipulating paths without I/O.
PurePath represents a filesystem path and offers operations which
don't imply any actual filesystem I/O. Depending on your system,
instantiating a PurePath will return either a PurePosixPath or a
PureWindowsPath object. You can also instantiate either of these classes
directly, regardless of your system.
"""
__slots__= (
'_drv', '_root', '_parts',
'_str', '_hash', '_pparts', '_cached_cparts',
)
def__new__(cls, *args):
"""Construct a PurePath from one or several strings and or existing
PurePath objects. The strings and path objects are combined so as
to yield a canonicalized path, which is incorporated into the
new PurePath object.
"""
ifclsisPurePath:
cls=PureWindowsPathifos.name=='nt'elsePurePosixPath
returncls._from_parts(args)
def__reduce__(self):
# Using the parts tuple helps share interned path parts
# when pickling related paths.
return (self.__class__, tuple(self._parts))
@classmethod
def_parse_args(cls, args):
# This is useful when you don't want to create an instance, just
# canonicalize some constructor arguments.
parts= []
forainargs:
ifisinstance(a, PurePath):
parts+=a._parts
else:
a=os.fspath(a)
ifisinstance(a, str):
# Force-cast str subclasses to str (issue #21127)
parts.append(str(a))
else:
raiseTypeError(
"argument should be a str object or an os.PathLike "
"object returning str, not %r"
%type(a))
returncls._flavour.parse_parts(parts)
@classmethod
def_from_parts(cls, args):
# We need to call _parse_args on the instance, so as to get the
# right flavour.
self=object.__new__(cls)
drv, root, parts=self._parse_args(args)
self._drv=drv
self._root=root
self._parts=parts
returnself
@classmethod
def_from_parsed_parts(cls, drv, root, parts):
self=object.__new__(cls)
self._drv=drv
self._root=root
self._parts=parts
returnself
@classmethod
def_format_parsed_parts(cls, drv, root, parts):
ifdrvorroot:
returndrv+root+cls._flavour.join(parts[1:])
else:
returncls._flavour.join(parts)
def_make_child(self, args):
drv, root, parts=self._parse_args(args)
drv, root, parts=self._flavour.join_parsed_parts(
self._drv, self._root, self._parts, drv, root, parts)
returnself._from_parsed_parts(drv, root, parts)
def__str__(self):
"""Return the string representation of the path, suitable for
passing to system calls."""
try:
returnself._str
exceptAttributeError:
self._str=self._format_parsed_parts(self._drv, self._root,
self._parts) or'.'
returnself._str
def__fspath__(self):
returnstr(self)
defas_posix(self):
"""Return the string representation of the path with forward (/)
slashes."""
f=self._flavour
returnstr(self).replace(f.sep, '/')
def__bytes__(self):
"""Return the bytes representation of the path. This is only
recommended to use under Unix."""
returnos.fsencode(self)
def__repr__(self):
return"{}({!r})".format(self.__class__.__name__, self.as_posix())
defas_uri(self):
"""Return the path as a 'file' URI."""
ifnotself.is_absolute():
raiseValueError("relative path can't be expressed as a file URI")
returnself._flavour.make_uri(self)
@property
def_cparts(self):
# Cached casefolded parts, for hashing and comparison
try:
returnself._cached_cparts
exceptAttributeError:
self._cached_cparts=self._flavour.casefold_parts(self._parts)
returnself._cached_cparts
def__eq__(self, other):
ifnotisinstance(other, PurePath):
returnNotImplemented
returnself._cparts==other._cpartsandself._flavourisother._flavour
def__hash__(self):
try:
returnself._hash
exceptAttributeError:
self._hash=hash(tuple(self._cparts))
returnself._hash
def__lt__(self, other):
ifnotisinstance(other, PurePath) orself._flavourisnotother._flavour:
returnNotImplemented
returnself._cparts<other._cparts
def__le__(self, other):
ifnotisinstance(other, PurePath) orself._flavourisnotother._flavour:
returnNotImplemented
returnself._cparts<=other._cparts
def__gt__(self, other):
ifnotisinstance(other, PurePath) orself._flavourisnotother._flavour:
returnNotImplemented
returnself._cparts>other._cparts
def__ge__(self, other):
ifnotisinstance(other, PurePath) orself._flavourisnotother._flavour:
returnNotImplemented
returnself._cparts>=other._cparts
drive=property(attrgetter('_drv'),
doc="""The drive prefix (letter or UNC path), if any.""")
root=property(attrgetter('_root'),
doc="""The root of the path, if any.""")
@property
defanchor(self):
"""The concatenation of the drive and root, or ''."""
anchor=self._drv+self._root
returnanchor
@property
defname(self):
"""The final path component, if any."""
parts=self._parts
iflen(parts) == (1if (self._drvorself._root) else0):
return''
returnparts[-1]
@property
defsuffix(self):
"""
The final component's last suffix, if any.
This includes the leading period. For example: '.txt'
"""
name=self.name
i=name.rfind('.')
if0<i<len(name) -1:
returnname[i:]
else:
return''
@property
defsuffixes(self):
"""
A list of the final component's suffixes, if any.
These include the leading periods. For example: ['.tar', '.gz']
"""
name=self.name
ifname.endswith('.'):
return []
name=name.lstrip('.')
return ['.'+suffixforsuffixinname.split('.')[1:]]
@property
defstem(self):
"""The final path component, minus its last suffix."""
name=self.name
i=name.rfind('.')
if0<i<len(name) -1:
returnname[:i]
else:
returnname
defwith_name(self, name):
"""Return a new path with the file name changed."""
ifnotself.name:
raiseValueError("%r has an empty name"% (self,))
drv, root, parts=self._flavour.parse_parts((name,))
if (notnameorname[-1] in [self._flavour.sep, self._flavour.altsep]
ordrvorrootorlen(parts) !=1):
raiseValueError("Invalid name %r"% (name))
returnself._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name])
defwith_stem(self, stem):
"""Return a new path with the stem changed."""
returnself.with_name(stem+self.suffix)
defwith_suffix(self, suffix):
"""Return a new path with the file suffix changed. If the path
has no suffix, add given suffix. If the given suffix is an empty
string, remove the suffix from the path.
"""
f=self._flavour
iff.sepinsuffixorf.altsepandf.altsepinsuffix:
raiseValueError("Invalid suffix %r"% (suffix,))
ifsuffixandnotsuffix.startswith('.') orsuffix=='.':
raiseValueError("Invalid suffix %r"% (suffix))
name=self.name
ifnotname:
raiseValueError("%r has an empty name"% (self,))
old_suffix=self.suffix
ifnotold_suffix:
name=name+suffix
else:
name=name[:-len(old_suffix)] +suffix
returnself._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name])
defrelative_to(self, *other):
"""Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError.
"""
# For the purpose of this method, drive and root are considered
# separate parts, i.e.:
# Path('c:/').relative_to('c:') gives Path('/')
# Path('c:/').relative_to('/') raise ValueError
ifnotother:
raiseTypeError("need at least one argument")
parts=self._parts
drv=self._drv
root=self._root
ifroot:
abs_parts= [drv, root] +parts[1:]
else:
abs_parts=parts
to_drv, to_root, to_parts=self._parse_args(other)
ifto_root:
to_abs_parts= [to_drv, to_root] +to_parts[1:]
else:
to_abs_parts=to_parts
n=len(to_abs_parts)
cf=self._flavour.casefold_parts
if (rootordrv) ifn==0elsecf(abs_parts[:n]) !=cf(to_abs_parts):
formatted=self._format_parsed_parts(to_drv, to_root, to_parts)
raiseValueError("{!r} is not in the subpath of {!r}"
" OR one path is relative and the other is absolute."
.format(str(self), str(formatted)))
returnself._from_parsed_parts('', rootifn==1else'',
abs_parts[n:])
defis_relative_to(self, *other):
"""Return True if the path is relative to another path or False.
"""
try:
self.relative_to(*other)
returnTrue
exceptValueError:
returnFalse
@property
defparts(self):
"""An object providing sequence-like access to the
components in the filesystem path."""
# We cache the tuple to avoid building a new one each time .parts
# is accessed. XXX is this necessary?
try:
returnself._pparts
exceptAttributeError:
self._pparts=tuple(self._parts)
returnself._pparts
defjoinpath(self, *args):
"""Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored).
"""
returnself._make_child(args)
def__truediv__(self, key):
try:
returnself._make_child((key,))
exceptTypeError:
returnNotImplemented
def__rtruediv__(self, key):
try:
returnself._from_parts([key] +self._parts)
exceptTypeError:
returnNotImplemented
@property
defparent(self):
"""The logical parent of the path."""
drv=self._drv
root=self._root
parts=self._parts
iflen(parts) ==1and (drvorroot):
returnself
returnself._from_parsed_parts(drv, root, parts[:-1])
@property
defparents(self):
"""A sequence of this path's logical parents."""
return_PathParents(self)
defis_absolute(self):
"""True if the path is absolute (has both a root and, if applicable,
a drive)."""
ifnotself._root:
returnFalse
returnnotself._flavour.has_drvorbool(self._drv)
defis_reserved(self):
"""Return True if the path contains one of the special names reserved
by the system, if any."""
returnself._flavour.is_reserved(self._parts)
defmatch(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf=self._flavour.casefold
path_pattern=cf(path_pattern)
drv, root, pat_parts=self._flavour.parse_parts((path_pattern,))
ifnotpat_parts:
raiseValueError("empty pattern")
ifdrvanddrv!=cf(self._drv):
returnFalse
ifrootandroot!=cf(self._root):
returnFalse
parts=self._cparts
ifdrvorroot:
iflen(pat_parts) !=len(parts):
returnFalse
pat_parts=pat_parts[1:]
eliflen(pat_parts) >len(parts):
returnFalse
forpart, patinzip(reversed(parts), reversed(pat_parts)):
ifnotfnmatch.fnmatchcase(part, pat):
returnFalse
returnTrue
# Can't subclass os.PathLike from PurePath and keep the constructor
# optimizations in PurePath._parse_args().
os.PathLike.register(PurePath)
classPurePosixPath(PurePath):
"""PurePath subclass for non-Windows systems.
On a POSIX system, instantiating a PurePath should return this object.
However, you can also instantiate it directly on any system.
"""
_flavour=_posix_flavour
__slots__= ()
classPureWindowsPath(PurePath):
"""PurePath subclass for Windows systems.
On a Windows system, instantiating a PurePath should return this object.
However, you can also instantiate it directly on any system.
"""
_flavour=_windows_flavour
__slots__= ()
# Filesystem-accessing classes
classPath(PurePath):
"""PurePath subclass that can make system calls.
Path represents a filesystem path but unlike PurePath, also offers
methods to do system calls on path objects. Depending on your system,
instantiating a Path will return either a PosixPath or a WindowsPath
object. You can also instantiate a PosixPath or WindowsPath directly,
but cannot instantiate a WindowsPath on a POSIX system or vice versa.
"""
__slots__= ()
def__new__(cls, *args, **kwargs):
ifclsisPath:
cls=WindowsPathifos.name=='nt'elsePosixPath
self=cls._from_parts(args)
ifnotself._flavour.is_supported:
raiseNotImplementedError("cannot instantiate %r on your system"
% (cls.__name__,))
returnself
def_make_child_relpath(self, part):
# This is an optimization used for dir walking. `part` must be
# a single part relative to this path.
parts=self._parts+ [part]
returnself._from_parsed_parts(self._drv, self._root, parts)
def__enter__(self):
# In previous versions of pathlib, __exit__() marked this path as
# closed; subsequent attempts to perform I/O would raise an IOError.
# This functionality was never documented, and had the effect of
# making Path objects mutable, contrary to PEP 428.
# In Python 3.9 __exit__() was made a no-op.
# In Python 3.11 __enter__() began emitting DeprecationWarning.
# In Python 3.13 __enter__() and __exit__() should be removed.
warnings.warn("pathlib.Path.__enter__() is deprecated and scheduled "
"for removal in Python 3.13; Path objects as a context "
"manager is a no-op",
DeprecationWarning, stacklevel=2)
returnself
def__exit__(self, t, v, tb):
pass
# Public API
@classmethod
defcwd(cls):
"""Return a new path pointing to the current working directory
(as returned by os.getcwd()).
"""
returncls(os.getcwd())
@classmethod
defhome(cls):
"""Return a new path pointing to the user's home directory (as
returned by os.path.expanduser('~')).
"""
returncls("~").expanduser()
defsamefile(self, other_path):
"""Return whether other_path is the same or not as this file
(as returned by os.path.samefile()).
"""
st=self.stat()
try:
other_st=other_path.stat()
exceptAttributeError:
other_st=self.__class__(other_path).stat()
returnos.path.samestat(st, other_st)
defiterdir(self):
"""Iterate over the files in this directory. Does not yield any
result for the special paths '.' and '..'.
"""
fornameinos.listdir(self):
yieldself._make_child_relpath(name)
def_scandir(self):
# bpo-24132: a future version of pathlib will support subclassing of
# pathlib.Path to customize how the filesystem is accessed. This
# includes scandir(), which is used to implement glob().
returnos.scandir(self)
defglob(self, pattern):
"""Iterate over this subtree and yield all existing files (of any
kind, including directories) matching the given relative pattern.
"""
sys.audit("pathlib.Path.glob", self, pattern)
ifnotpattern:
raiseValueError("Unacceptable pattern: {!r}".format(pattern))
drv, root, pattern_parts=self._flavour.parse_parts((pattern,))
ifdrvorroot:
raiseNotImplementedError("Non-relative patterns are unsupported")
ifpattern[-1] in (self._flavour.sep, self._flavour.altsep):
pattern_parts.append('')
selector=_make_selector(tuple(pattern_parts), self._flavour)
forpinselector.select_from(self):
yieldp
defrglob(self, pattern):
"""Recursively yield all existing files (of any kind, including
directories) matching the given relative pattern, anywhere in
this subtree.
"""
sys.audit("pathlib.Path.rglob", self, pattern)
drv, root, pattern_parts=self._flavour.parse_parts((pattern,))
ifdrvorroot:
raiseNotImplementedError("Non-relative patterns are unsupported")
ifpatternandpattern[-1] in (self._flavour.sep, self._flavour.altsep):
pattern_parts.append('')
selector=_make_selector(("**",) +tuple(pattern_parts), self._flavour)
forpinselector.select_from(self):
yieldp
defabsolute(self):
"""Return an absolute version of this path by prepending the current
working directory. No normalization or symlink resolution is performed.
Use resolve() to get the canonical path to a file.
"""
ifself.is_absolute():
returnself
returnself._from_parts([self.cwd()] +self._parts)
defresolve(self, strict=False):
"""
Make the path absolute, resolving all symlinks on the way and also
normalizing it.
"""
defcheck_eloop(e):
winerror=getattr(e, 'winerror', 0)
ife.errno==ELOOPorwinerror==_WINERROR_CANT_RESOLVE_FILENAME:
raiseRuntimeError("Symlink loop from %r"%e.filename)
try:
s=os.path.realpath(self, strict=strict)
exceptOSErrorase:
check_eloop(e)
raise
p=self._from_parts((s,))
# In non-strict mode, realpath() doesn't raise on symlink loops.
# Ensure we get an exception by calling stat()