pathlib — Object-oriented filesystem paths — Python 3.10.4 ...

文章推薦指數: 80 %
投票人數:10人

PEP 428: The pathlib module – object-oriented filesystem paths. See also ... The slash operator helps create child paths, similarly to os.path.join() : > ... Navigation index modules| next| previous| Python» 3.10.4Documentation» ThePythonStandardLibrary» FileandDirectoryAccess» pathlib—Object-orientedfilesystempaths | pathlib—Object-orientedfilesystempaths¶ Newinversion3.4. Sourcecode:Lib/pathlib.py Thismoduleoffersclassesrepresentingfilesystempathswithsemantics appropriatefordifferentoperatingsystems.Pathclassesaredivided betweenpurepaths,whichprovidepurelycomputational operationswithoutI/O,andconcretepaths,which inheritfrompurepathsbutalsoprovideI/Ooperations. Ifyou’veneverusedthismodulebeforeorjustaren’tsurewhichclassis rightforyourtask,Pathismostlikelywhatyouneed.Itinstantiates aconcretepathfortheplatformthecodeisrunningon. Purepathsareusefulinsomespecialcases;forexample: IfyouwanttomanipulateWindowspathsonaUnixmachine(orviceversa). YoucannotinstantiateaWindowsPathwhenrunningonUnix,butyou caninstantiatePureWindowsPath. Youwanttomakesurethatyourcodeonlymanipulatespathswithoutactually accessingtheOS.Inthiscase,instantiatingoneofthepureclassesmaybe usefulsincethosesimplydon’thaveanyOS-accessingoperations. Seealso PEP428:Thepathlibmodule–object-orientedfilesystempaths. Seealso Forlow-levelpathmanipulationonstrings,youcanalsousethe os.pathmodule. Basicuse¶ Importingthemainclass: >>>frompathlibimportPath Listingsubdirectories: >>>p=Path('.') >>>[xforxinp.iterdir()ifx.is_dir()] [PosixPath('.hg'),PosixPath('docs'),PosixPath('dist'), PosixPath('__pycache__'),PosixPath('build')] ListingPythonsourcefilesinthisdirectorytree: >>>list(p.glob('**/*.py')) [PosixPath('test_pathlib.py'),PosixPath('setup.py'), PosixPath('pathlib.py'),PosixPath('docs/conf.py'), PosixPath('build/lib/pathlib.py')] Navigatinginsideadirectorytree: >>>p=Path('/etc') >>>q=p/'init.d'/'reboot' >>>q PosixPath('/etc/init.d/reboot') >>>q.resolve() PosixPath('/etc/rc.d/init.d/halt') Queryingpathproperties: >>>q.exists() True >>>q.is_dir() False Openingafile: >>>withq.open()asf:f.readline() ... '#!/bin/bash\n' Purepaths¶ Purepathobjectsprovidepath-handlingoperationswhichdon’tactually accessafilesystem.Therearethreewaystoaccesstheseclasses,which wealsocallflavours: classpathlib.PurePath(*pathsegments)¶ Agenericclassthatrepresentsthesystem’spathflavour(instantiating itcreateseitheraPurePosixPathoraPureWindowsPath): >>>PurePath('setup.py')#RunningonaUnixmachine PurePosixPath('setup.py') Eachelementofpathsegmentscanbeeitherastringrepresentinga pathsegment,anobjectimplementingtheos.PathLikeinterface whichreturnsastring,oranotherpathobject: >>>PurePath('foo','some/path','bar') PurePosixPath('foo/some/path/bar') >>>PurePath(Path('foo'),Path('bar')) PurePosixPath('foo/bar') Whenpathsegmentsisempty,thecurrentdirectoryisassumed: >>>PurePath() PurePosixPath('.') Whenseveralabsolutepathsaregiven,thelastistakenasananchor (mimickingos.path.join()’sbehaviour): >>>PurePath('/etc','/usr','lib64') PurePosixPath('/usr/lib64') >>>PureWindowsPath('c:/Windows','d:bar') PureWindowsPath('d:bar') However,inaWindowspath,changingthelocalrootdoesn’tdiscardthe previousdrivesetting: >>>PureWindowsPath('c:/Windows','/ProgramFiles') PureWindowsPath('c:/ProgramFiles') Spuriousslashesandsingledotsarecollapsed,butdoubledots('..') arenot,sincethiswouldchangethemeaningofapathinthefaceof symboliclinks: >>>PurePath('foo//bar') PurePosixPath('foo/bar') >>>PurePath('foo/./bar') PurePosixPath('foo/bar') >>>PurePath('foo/../bar') PurePosixPath('foo/../bar') (anaïveapproachwouldmakePurePosixPath('foo/../bar')equivalent toPurePosixPath('bar'),whichiswrongiffooisasymboliclink toanotherdirectory) Purepathobjectsimplementtheos.PathLikeinterface,allowingthem tobeusedanywheretheinterfaceisaccepted. Changedinversion3.6:Addedsupportfortheos.PathLikeinterface. classpathlib.PurePosixPath(*pathsegments)¶ AsubclassofPurePath,thispathflavourrepresentsnon-Windows filesystempaths: >>>PurePosixPath('/etc') PurePosixPath('/etc') pathsegmentsisspecifiedsimilarlytoPurePath. classpathlib.PureWindowsPath(*pathsegments)¶ AsubclassofPurePath,thispathflavourrepresentsWindows filesystempaths: >>>PureWindowsPath('c:/ProgramFiles/') PureWindowsPath('c:/ProgramFiles') pathsegmentsisspecifiedsimilarlytoPurePath. Regardlessofthesystemyou’rerunningon,youcaninstantiateallof theseclasses,sincetheydon’tprovideanyoperationthatdoessystemcalls. Generalproperties¶ Pathsareimmutableandhashable.Pathsofasameflavourarecomparable andorderable.Thesepropertiesrespecttheflavour’scase-folding semantics: >>>PurePosixPath('foo')==PurePosixPath('FOO') False >>>PureWindowsPath('foo')==PureWindowsPath('FOO') True >>>PureWindowsPath('FOO')in{PureWindowsPath('foo')} True >>>PureWindowsPath('C:')>>PureWindowsPath('foo')==PurePosixPath('foo') False >>>PureWindowsPath('foo')",line1,in TypeError:'>>p=PurePath('/etc') >>>p PurePosixPath('/etc') >>>p/'init.d'/'apache2' PurePosixPath('/etc/init.d/apache2') >>>q=PurePath('bin') >>>'/usr'/q PurePosixPath('/usr/bin') Apathobjectcanbeusedanywhereanobjectimplementingos.PathLike isaccepted: >>>importos >>>p=PurePath('/etc') >>>os.fspath(p) '/etc' Thestringrepresentationofapathistherawfilesystempathitself (innativeform,e.g.withbackslashesunderWindows),whichyoucan passtoanyfunctiontakingafilepathasastring: >>>p=PurePath('/etc') >>>str(p) '/etc' >>>p=PureWindowsPath('c:/ProgramFiles') >>>str(p) 'c:\\ProgramFiles' Similarly,callingbytesonapathgivestherawfilesystempathasa bytesobject,asencodedbyos.fsencode(): >>>bytes(p) b'/etc' Note CallingbytesisonlyrecommendedunderUnix.UnderWindows, theunicodeformisthecanonicalrepresentationoffilesystempaths. Accessingindividualparts¶ Toaccesstheindividual“parts”(components)ofapath,usethefollowing property: PurePath.parts¶ Atuplegivingaccesstothepath’svariouscomponents: >>>p=PurePath('/usr/bin/python3') >>>p.parts ('/','usr','bin','python3') >>>p=PureWindowsPath('c:/ProgramFiles/PSF') >>>p.parts ('c:\\','ProgramFiles','PSF') (notehowthedriveandlocalrootareregroupedinasinglepart) Methodsandproperties¶ Purepathsprovidethefollowingmethodsandproperties: PurePath.drive¶ Astringrepresentingthedriveletterorname,ifany: >>>PureWindowsPath('c:/ProgramFiles/').drive 'c:' >>>PureWindowsPath('/ProgramFiles/').drive '' >>>PurePosixPath('/etc').drive '' UNCsharesarealsoconsidereddrives: >>>PureWindowsPath('//host/share/foo.txt').drive '\\\\host\\share' PurePath.root¶ Astringrepresentingthe(localorglobal)root,ifany: >>>PureWindowsPath('c:/ProgramFiles/').root '\\' >>>PureWindowsPath('c:ProgramFiles/').root '' >>>PurePosixPath('/etc').root '/' UNCsharesalwayshavearoot: >>>PureWindowsPath('//host/share').root '\\' PurePath.anchor¶ Theconcatenationofthedriveandroot: >>>PureWindowsPath('c:/ProgramFiles/').anchor 'c:\\' >>>PureWindowsPath('c:ProgramFiles/').anchor 'c:' >>>PurePosixPath('/etc').anchor '/' >>>PureWindowsPath('//host/share').anchor '\\\\host\\share\\' PurePath.parents¶ Animmutablesequenceprovidingaccesstothelogicalancestorsof thepath: >>>p=PureWindowsPath('c:/foo/bar/setup.py') >>>p.parents[0] PureWindowsPath('c:/foo/bar') >>>p.parents[1] PureWindowsPath('c:/foo') >>>p.parents[2] PureWindowsPath('c:/') Changedinversion3.10:Theparentssequencenowsupportsslicesandnegativeindexvalues. PurePath.parent¶ Thelogicalparentofthepath: >>>p=PurePosixPath('/a/b/c/d') >>>p.parent PurePosixPath('/a/b/c') Youcannotgopastananchor,oremptypath: >>>p=PurePosixPath('/') >>>p.parent PurePosixPath('/') >>>p=PurePosixPath('.') >>>p.parent PurePosixPath('.') Note Thisisapurelylexicaloperation,hencethefollowingbehaviour: >>>p=PurePosixPath('foo/..') >>>p.parent PurePosixPath('foo') Ifyouwanttowalkanarbitraryfilesystempathupwards,itis recommendedtofirstcallPath.resolve()soastoresolve symlinksandeliminate“..”components. PurePath.name¶ Astringrepresentingthefinalpathcomponent,excludingthedriveand root,ifany: >>>PurePosixPath('my/library/setup.py').name 'setup.py' UNCdrivenamesarenotconsidered: >>>PureWindowsPath('//some/share/setup.py').name 'setup.py' >>>PureWindowsPath('//some/share').name '' PurePath.suffix¶ Thefileextensionofthefinalcomponent,ifany: >>>PurePosixPath('my/library/setup.py').suffix '.py' >>>PurePosixPath('my/library.tar.gz').suffix '.gz' >>>PurePosixPath('my/library').suffix '' PurePath.suffixes¶ Alistofthepath’sfileextensions: >>>PurePosixPath('my/library.tar.gar').suffixes ['.tar','.gar'] >>>PurePosixPath('my/library.tar.gz').suffixes ['.tar','.gz'] >>>PurePosixPath('my/library').suffixes [] PurePath.stem¶ Thefinalpathcomponent,withoutitssuffix: >>>PurePosixPath('my/library.tar.gz').stem 'library.tar' >>>PurePosixPath('my/library.tar').stem 'library' >>>PurePosixPath('my/library').stem 'library' PurePath.as_posix()¶ Returnastringrepresentationofthepathwithforwardslashes(/): >>>p=PureWindowsPath('c:\\windows') >>>str(p) 'c:\\windows' >>>p.as_posix() 'c:/windows' PurePath.as_uri()¶ RepresentthepathasafileURI.ValueErrorisraisedif thepathisn’tabsolute. >>>p=PurePosixPath('/etc/passwd') >>>p.as_uri() 'file:///etc/passwd' >>>p=PureWindowsPath('c:/Windows') >>>p.as_uri() 'file:///c:/Windows' PurePath.is_absolute()¶ Returnwhetherthepathisabsoluteornot.Apathisconsideredabsolute ifithasbotharootand(iftheflavourallows)adrive: >>>PurePosixPath('/a/b').is_absolute() True >>>PurePosixPath('a/b').is_absolute() False >>>PureWindowsPath('c:/a/b').is_absolute() True >>>PureWindowsPath('/a/b').is_absolute() False >>>PureWindowsPath('c:').is_absolute() False >>>PureWindowsPath('//some/share').is_absolute() True PurePath.is_relative_to(*other)¶ Returnwhetherornotthispathisrelativetotheotherpath. >>>p=PurePath('/etc/passwd') >>>p.is_relative_to('/etc') True >>>p.is_relative_to('/usr') False Newinversion3.9. PurePath.is_reserved()¶ WithPureWindowsPath,returnTrueifthepathisconsidered reservedunderWindows,Falseotherwise.WithPurePosixPath, Falseisalwaysreturned. >>>PureWindowsPath('nul').is_reserved() True >>>PurePosixPath('nul').is_reserved() False Filesystemcallsonreservedpathscanfailmysteriouslyorhave unintendedeffects. PurePath.joinpath(*other)¶ Callingthismethodisequivalenttocombiningthepathwitheachof theotherargumentsinturn: >>>PurePosixPath('/etc').joinpath('passwd') PurePosixPath('/etc/passwd') >>>PurePosixPath('/etc').joinpath(PurePosixPath('passwd')) PurePosixPath('/etc/passwd') >>>PurePosixPath('/etc').joinpath('init.d','apache2') PurePosixPath('/etc/init.d/apache2') >>>PureWindowsPath('c:').joinpath('/ProgramFiles') PureWindowsPath('c:/ProgramFiles') PurePath.match(pattern)¶ Matchthispathagainsttheprovidedglob-stylepattern.ReturnTrue ifmatchingissuccessful,Falseotherwise. Ifpatternisrelative,thepathcanbeeitherrelativeorabsolute, andmatchingisdonefromtheright: >>>PurePath('a/b.py').match('*.py') True >>>PurePath('/a/b/c.py').match('b/*.py') True >>>PurePath('/a/b/c.py').match('a/*.py') False Ifpatternisabsolute,thepathmustbeabsolute,andthewholepath mustmatch: >>>PurePath('/a.py').match('/*.py') True >>>PurePath('a/b.py').match('/*.py') False Aswithothermethods,case-sensitivityfollowsplatformdefaults: >>>PurePosixPath('b.py').match('*.PY') False >>>PureWindowsPath('b.py').match('*.PY') True PurePath.relative_to(*other)¶ Computeaversionofthispathrelativetothepathrepresentedby other.Ifit’simpossible,ValueErrorisraised: >>>p=PurePosixPath('/etc/passwd') >>>p.relative_to('/') PurePosixPath('etc/passwd') >>>p.relative_to('/etc') PurePosixPath('passwd') >>>p.relative_to('/usr') Traceback(mostrecentcalllast): File"",line1,in File"pathlib.py",line694,inrelative_to .format(str(self),str(formatted))) ValueError:'/etc/passwd'isnotinthesubpathof'/usr'ORonepathisrelativeandtheotherabsolute. NOTE:ThisfunctionispartofPurePathandworkswithstrings.Itdoesnotcheckoraccesstheunderlyingfilestructure. PurePath.with_name(name)¶ Returnanewpathwiththenamechanged.Iftheoriginalpath doesn’thaveaname,ValueErrorisraised: >>>p=PureWindowsPath('c:/Downloads/pathlib.tar.gz') >>>p.with_name('setup.py') PureWindowsPath('c:/Downloads/setup.py') >>>p=PureWindowsPath('c:/') >>>p.with_name('setup.py') Traceback(mostrecentcalllast): File"",line1,in File"/home/antoine/cpython/default/Lib/pathlib.py",line751,inwith_name raiseValueError("%rhasanemptyname"%(self,)) ValueError:PureWindowsPath('c:/')hasanemptyname PurePath.with_stem(stem)¶ Returnanewpathwiththestemchanged.Iftheoriginalpath doesn’thaveaname,ValueErrorisraised: >>>p=PureWindowsPath('c:/Downloads/draft.txt') >>>p.with_stem('final') PureWindowsPath('c:/Downloads/final.txt') >>>p=PureWindowsPath('c:/Downloads/pathlib.tar.gz') >>>p.with_stem('lib') PureWindowsPath('c:/Downloads/lib.gz') >>>p=PureWindowsPath('c:/') >>>p.with_stem('') Traceback(mostrecentcalllast): File"",line1,in File"/home/antoine/cpython/default/Lib/pathlib.py",line861,inwith_stem returnself.with_name(stem+self.suffix) File"/home/antoine/cpython/default/Lib/pathlib.py",line851,inwith_name raiseValueError("%rhasanemptyname"%(self,)) ValueError:PureWindowsPath('c:/')hasanemptyname Newinversion3.9. PurePath.with_suffix(suffix)¶ Returnanewpathwiththesuffixchanged.Iftheoriginalpath doesn’thaveasuffix,thenewsuffixisappendedinstead.Ifthe suffixisanemptystring,theoriginalsuffixisremoved: >>>p=PureWindowsPath('c:/Downloads/pathlib.tar.gz') >>>p.with_suffix('.bz2') PureWindowsPath('c:/Downloads/pathlib.tar.bz2') >>>p=PureWindowsPath('README') >>>p.with_suffix('.txt') PureWindowsPath('README.txt') >>>p=PureWindowsPath('README.txt') >>>p.with_suffix('') PureWindowsPath('README') Concretepaths¶ Concretepathsaresubclassesofthepurepathclasses.Inadditionto operationsprovidedbythelatter,theyalsoprovidemethodstodosystem callsonpathobjects.Therearethreewaystoinstantiateconcretepaths: classpathlib.Path(*pathsegments)¶ AsubclassofPurePath,thisclassrepresentsconcretepathsof thesystem’spathflavour(instantiatingitcreateseithera PosixPathoraWindowsPath): >>>Path('setup.py') PosixPath('setup.py') pathsegmentsisspecifiedsimilarlytoPurePath. classpathlib.PosixPath(*pathsegments)¶ AsubclassofPathandPurePosixPath,thisclass representsconcretenon-Windowsfilesystempaths: >>>PosixPath('/etc') PosixPath('/etc') pathsegmentsisspecifiedsimilarlytoPurePath. classpathlib.WindowsPath(*pathsegments)¶ AsubclassofPathandPureWindowsPath,thisclass representsconcreteWindowsfilesystempaths: >>>WindowsPath('c:/ProgramFiles/') WindowsPath('c:/ProgramFiles') pathsegmentsisspecifiedsimilarlytoPurePath. Youcanonlyinstantiatetheclassflavourthatcorrespondstoyoursystem (allowingsystemcallsonnon-compatiblepathflavourscouldleadto bugsorfailuresinyourapplication): >>>importos >>>os.name 'posix' >>>Path('setup.py') PosixPath('setup.py') >>>PosixPath('setup.py') PosixPath('setup.py') >>>WindowsPath('setup.py') Traceback(mostrecentcalllast): File"",line1,in File"pathlib.py",line798,in__new__ %(cls.__name__,)) NotImplementedError:cannotinstantiate'WindowsPath'onyoursystem Methods¶ Concretepathsprovidethefollowingmethodsinadditiontopurepaths methods.ManyofthesemethodscanraiseanOSErrorifasystem callfails(forexamplebecausethepathdoesn’texist). Changedinversion3.8:exists(),is_dir(),is_file(), is_mount(),is_symlink(), is_block_device(),is_char_device(), is_fifo(),is_socket()nowreturnFalse insteadofraisinganexceptionforpathsthatcontaincharacters unrepresentableattheOSlevel. classmethodPath.cwd()¶ Returnanewpathobjectrepresentingthecurrentdirectory(asreturned byos.getcwd()): >>>Path.cwd() PosixPath('/home/antoine/pathlib') classmethodPath.home()¶ Returnanewpathobjectrepresentingtheuser’shomedirectory(as returnedbyos.path.expanduser()with~construct).Ifthehome directorycan’tberesolved,RuntimeErrorisraised. >>>Path.home() PosixPath('/home/antoine') Newinversion3.5. Path.stat(*,follow_symlinks=True)¶ Returnaos.stat_resultobjectcontaininginformationaboutthispath,likeos.stat(). Theresultislookedupateachcalltothismethod. Thismethodnormallyfollowssymlinks;tostatasymlinkaddtheargument follow_symlinks=False,oruselstat(). >>>p=Path('setup.py') >>>p.stat().st_size 956 >>>p.stat().st_mtime 1327883547.852554 Changedinversion3.10:Thefollow_symlinksparameterwasadded. Path.chmod(mode,*,follow_symlinks=True)¶ Changethefilemodeandpermissions,likeos.chmod(). Thismethodnormallyfollowssymlinks.SomeUnixflavourssupportchanging permissionsonthesymlinkitself;ontheseplatformsyoumayaddthe argumentfollow_symlinks=False,oruselchmod(). >>>p=Path('setup.py') >>>p.stat().st_mode 33277 >>>p.chmod(0o444) >>>p.stat().st_mode 33060 Changedinversion3.10:Thefollow_symlinksparameterwasadded. Path.exists()¶ Whetherthepathpointstoanexistingfileordirectory: >>>Path('.').exists() True >>>Path('setup.py').exists() True >>>Path('/etc').exists() True >>>Path('nonexistentfile').exists() False Note Ifthepathpointstoasymlink,exists()returnswhetherthe symlinkpointstoanexistingfileordirectory. Path.expanduser()¶ Returnanewpathwithexpanded~and~userconstructs, asreturnedbyos.path.expanduser().Ifahomedirectorycan’tbe resolved,RuntimeErrorisraised. >>>p=PosixPath('~/films/MontyPython') >>>p.expanduser() PosixPath('/home/eric/films/MontyPython') Newinversion3.5. Path.glob(pattern)¶ Globthegivenrelativepatterninthedirectoryrepresentedbythispath, yieldingallmatchingfiles(ofanykind): >>>sorted(Path('.').glob('*.py')) [PosixPath('pathlib.py'),PosixPath('setup.py'),PosixPath('test_pathlib.py')] >>>sorted(Path('.').glob('*/*.py')) [PosixPath('docs/conf.py')] Patternsarethesameasforfnmatch,withtheadditionof“**” whichmeans“thisdirectoryandallsubdirectories,recursively”.Inother words,itenablesrecursiveglobbing: >>>sorted(Path('.').glob('**/*.py')) [PosixPath('build/lib/pathlib.py'), PosixPath('docs/conf.py'), PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')] Note Usingthe“**”patterninlargedirectorytreesmayconsume aninordinateamountoftime. Raisesanauditingeventpathlib.Path.globwithargumentsself,pattern. Path.group()¶ Returnthenameofthegroupowningthefile.KeyErrorisraised ifthefile’sgidisn’tfoundinthesystemdatabase. Path.is_dir()¶ ReturnTrueifthepathpointstoadirectory(orasymboliclink pointingtoadirectory),Falseifitpointstoanotherkindoffile. Falseisalsoreturnedifthepathdoesn’texistorisabrokensymlink; othererrors(suchaspermissionerrors)arepropagated. Path.is_file()¶ ReturnTrueifthepathpointstoaregularfile(orasymboliclink pointingtoaregularfile),Falseifitpointstoanotherkindoffile. Falseisalsoreturnedifthepathdoesn’texistorisabrokensymlink; othererrors(suchaspermissionerrors)arepropagated. Path.is_mount()¶ ReturnTrueifthepathisamountpoint:apointina filesystemwhereadifferentfilesystemhasbeenmounted.OnPOSIX,the functioncheckswhetherpath’sparent,path/..,isonadifferent devicethanpath,orwhetherpath/..andpathpointtothesame i-nodeonthesamedevice—thisshoulddetectmountpointsforallUnix andPOSIXvariants.NotimplementedonWindows. Newinversion3.7. Path.is_symlink()¶ ReturnTrueifthepathpointstoasymboliclink,Falseotherwise. Falseisalsoreturnedifthepathdoesn’texist;othererrors(such aspermissionerrors)arepropagated. Path.is_socket()¶ ReturnTrueifthepathpointstoaUnixsocket(orasymboliclink pointingtoaUnixsocket),Falseifitpointstoanotherkindoffile. Falseisalsoreturnedifthepathdoesn’texistorisabrokensymlink; othererrors(suchaspermissionerrors)arepropagated. Path.is_fifo()¶ ReturnTrueifthepathpointstoaFIFO(orasymboliclink pointingtoaFIFO),Falseifitpointstoanotherkindoffile. Falseisalsoreturnedifthepathdoesn’texistorisabrokensymlink; othererrors(suchaspermissionerrors)arepropagated. Path.is_block_device()¶ ReturnTrueifthepathpointstoablockdevice(orasymboliclink pointingtoablockdevice),Falseifitpointstoanotherkindoffile. Falseisalsoreturnedifthepathdoesn’texistorisabrokensymlink; othererrors(suchaspermissionerrors)arepropagated. Path.is_char_device()¶ ReturnTrueifthepathpointstoacharacterdevice(orasymboliclink pointingtoacharacterdevice),Falseifitpointstoanotherkindoffile. Falseisalsoreturnedifthepathdoesn’texistorisabrokensymlink; othererrors(suchaspermissionerrors)arepropagated. Path.iterdir()¶ Whenthepathpointstoadirectory,yieldpathobjectsofthedirectory contents: >>>p=Path('docs') >>>forchildinp.iterdir():child ... PosixPath('docs/conf.py') PosixPath('docs/_templates') PosixPath('docs/make.bat') PosixPath('docs/index.rst') PosixPath('docs/_build') PosixPath('docs/_static') PosixPath('docs/Makefile') Thechildrenareyieldedinarbitraryorder,andthespecialentries '.'and'..'arenotincluded.Ifafileisremovedfromoradded tothedirectoryaftercreatingtheiterator,whetherapathobjectfor thatfilebeincludedisunspecified. Path.lchmod(mode)¶ LikePath.chmod()but,ifthepathpointstoasymboliclink,the symboliclink’smodeischangedratherthanitstarget’s. Path.lstat()¶ LikePath.stat()but,ifthepathpointstoasymboliclink,return thesymboliclink’sinformationratherthanitstarget’s. Path.mkdir(mode=511,parents=False,exist_ok=False)¶ Createanewdirectoryatthisgivenpath.Ifmodeisgiven,itis combinedwiththeprocess’umaskvaluetodeterminethefilemode andaccessflags.Ifthepathalreadyexists,FileExistsError israised. Ifparentsistrue,anymissingparentsofthispatharecreated asneeded;theyarecreatedwiththedefaultpermissionswithouttaking modeintoaccount(mimickingthePOSIXmkdir-pcommand). Ifparentsisfalse(thedefault),amissingparentraises FileNotFoundError. Ifexist_okisfalse(thedefault),FileExistsErroris raisedifthetargetdirectoryalreadyexists. Ifexist_okistrue,FileExistsErrorexceptionswillbe ignored(samebehaviorasthePOSIXmkdir-pcommand),butonlyifthe lastpathcomponentisnotanexistingnon-directoryfile. Changedinversion3.5:Theexist_okparameterwasadded. Path.open(mode='r',buffering=-1,encoding=None,errors=None,newline=None)¶ Openthefilepointedtobythepath,likethebuilt-inopen() functiondoes: >>>p=Path('setup.py') >>>withp.open()asf: ...f.readline() ... '#!/usr/bin/envpython3\n' Path.owner()¶ Returnthenameoftheuserowningthefile.KeyErrorisraised ifthefile’suidisn’tfoundinthesystemdatabase. Path.read_bytes()¶ Returnthebinarycontentsofthepointed-tofileasabytesobject: >>>p=Path('my_binary_file') >>>p.write_bytes(b'Binaryfilecontents') 20 >>>p.read_bytes() b'Binaryfilecontents' Newinversion3.5. Path.read_text(encoding=None,errors=None)¶ Returnthedecodedcontentsofthepointed-tofileasastring: >>>p=Path('my_text_file') >>>p.write_text('Textfilecontents') 18 >>>p.read_text() 'Textfilecontents' Thefileisopenedandthenclosed.Theoptionalparametershavethesame meaningasinopen(). Newinversion3.5. Path.readlink()¶ Returnthepathtowhichthesymboliclinkpoints(asreturnedby os.readlink()): >>>p=Path('mylink') >>>p.symlink_to('setup.py') >>>p.readlink() PosixPath('setup.py') Newinversion3.9. Path.rename(target)¶ Renamethisfileordirectorytothegiventarget,andreturnanewPath instancepointingtotarget.OnUnix,iftargetexistsandisafile, itwillbereplacedsilentlyiftheuserhaspermission.targetcanbe eitherastringoranotherpathobject: >>>p=Path('foo') >>>p.open('w').write('sometext') 9 >>>target=Path('bar') >>>p.rename(target) PosixPath('bar') >>>target.open().read() 'sometext' Thetargetpathmaybeabsoluteorrelative.Relativepathsareinterpreted relativetothecurrentworkingdirectory,notthedirectoryofthePath object. Changedinversion3.8:Addedreturnvalue,returnthenewPathinstance. Path.replace(target)¶ Renamethisfileordirectorytothegiventarget,andreturnanewPath instancepointingtotarget.Iftargetpointstoanexistingfileor directory,itwillbeunconditionallyreplaced. Thetargetpathmaybeabsoluteorrelative.Relativepathsareinterpreted relativetothecurrentworkingdirectory,notthedirectoryofthePath object. Changedinversion3.8:Addedreturnvalue,returnthenewPathinstance. Path.resolve(strict=False)¶ Makethepathabsolute,resolvinganysymlinks.Anewpathobjectis returned: >>>p=Path() >>>p PosixPath('.') >>>p.resolve() PosixPath('/home/antoine/pathlib') “..”componentsarealsoeliminated(thisistheonlymethodtodoso): >>>p=Path('docs/../setup.py') >>>p.resolve() PosixPath('/home/antoine/pathlib/setup.py') Ifthepathdoesn’texistandstrictisTrue,FileNotFoundError israised.IfstrictisFalse,thepathisresolvedasfaraspossible andanyremainderisappendedwithoutcheckingwhetheritexists.Ifan infiniteloopisencounteredalongtheresolutionpath,RuntimeError israised. Newinversion3.6:Thestrictargument(pre-3.6behaviorisstrict). Path.rglob(pattern)¶ ThisislikecallingPath.glob()with“**/”addedinfrontofthe givenrelativepattern: >>>sorted(Path().rglob("*.py")) [PosixPath('build/lib/pathlib.py'), PosixPath('docs/conf.py'), PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')] Raisesanauditingeventpathlib.Path.rglobwithargumentsself,pattern. Path.rmdir()¶ Removethisdirectory.Thedirectorymustbeempty. Path.samefile(other_path)¶ Returnwhetherthispathpointstothesamefileasother_path,which canbeeitheraPathobject,orastring.Thesemanticsaresimilar toos.path.samefile()andos.path.samestat(). AnOSErrorcanberaisedifeitherfilecannotbeaccessedforsome reason. >>>p=Path('spam') >>>q=Path('eggs') >>>p.samefile(q) False >>>p.samefile('spam') True Newinversion3.5. Path.symlink_to(target,target_is_directory=False)¶ Makethispathasymboliclinktotarget.UnderWindows, target_is_directorymustbetrue(defaultFalse)ifthelink’starget isadirectory.UnderPOSIX,target_is_directory’svalueisignored. >>>p=Path('mylink') >>>p.symlink_to('setup.py') >>>p.resolve() PosixPath('/home/antoine/pathlib/setup.py') >>>p.stat().st_size 956 >>>p.lstat().st_size 8 Note Theorderofarguments(link,target)isthereverse ofos.symlink()’s. Path.hardlink_to(target)¶ Makethispathahardlinktothesamefileastarget. Note Theorderofarguments(link,target)isthereverse ofos.link()’s. Newinversion3.10. Path.link_to(target)¶ Maketargetahardlinktothispath. Warning Thisfunctiondoesnotmakethispathahardlinktotarget,despite theimplicationofthefunctionandargumentnames.Theargumentorder (target,link)isthereverseofPath.symlink_to()and Path.hardlink_to(),butmatchesthatofos.link(). Newinversion3.8. Deprecatedsinceversion3.10:ThismethodisdeprecatedinfavorofPath.hardlink_to(),asthe argumentorderofPath.link_to()doesnotmatchthatof Path.symlink_to(). Path.touch(mode=438,exist_ok=True)¶ Createafileatthisgivenpath.Ifmodeisgiven,itiscombined withtheprocess’umaskvaluetodeterminethefilemodeandaccess flags.Ifthefilealreadyexists,thefunctionsucceedsifexist_ok istrue(anditsmodificationtimeisupdatedtothecurrenttime), otherwiseFileExistsErrorisraised. Path.unlink(missing_ok=False)¶ Removethisfileorsymboliclink.Ifthepathpointstoadirectory, usePath.rmdir()instead. Ifmissing_okisfalse(thedefault),FileNotFoundErroris raisedifthepathdoesnotexist. Ifmissing_okistrue,FileNotFoundErrorexceptionswillbe ignored(samebehaviorasthePOSIXrm-fcommand). Changedinversion3.8:Themissing_okparameterwasadded. Path.write_bytes(data)¶ Openthefilepointedtoinbytesmode,writedatatoit,andclosethe file: >>>p=Path('my_binary_file') >>>p.write_bytes(b'Binaryfilecontents') 20 >>>p.read_bytes() b'Binaryfilecontents' Anexistingfileofthesamenameisoverwritten. Newinversion3.5. Path.write_text(data,encoding=None,errors=None,newline=None)¶ Openthefilepointedtointextmode,writedatatoit,andclosethe file: >>>p=Path('my_text_file') >>>p.write_text('Textfilecontents') 18 >>>p.read_text() 'Textfilecontents' Anexistingfileofthesamenameisoverwritten.Theoptionalparameters havethesamemeaningasinopen(). Newinversion3.5. Changedinversion3.10:Thenewlineparameterwasadded. Correspondencetotoolsintheosmodule¶ Belowisatablemappingvariousosfunctionstotheircorresponding PurePath/Pathequivalent. Note Notallpairsoffunctions/methodsbelowareequivalent.Someofthem, despitehavingsomeoverlappinguse-cases,havedifferentsemantics.They includeos.path.abspath()andPath.resolve(), os.path.relpath()andPurePath.relative_to(). os.path.abspath() Path.resolve()1 os.chmod() Path.chmod() os.mkdir() Path.mkdir() os.makedirs() Path.mkdir() os.rename() Path.rename() os.replace() Path.replace() os.rmdir() Path.rmdir() os.remove(),os.unlink() Path.unlink() os.getcwd() Path.cwd() os.path.exists() Path.exists() os.path.expanduser() Path.expanduser()and Path.home() os.listdir() Path.iterdir() os.path.isdir() Path.is_dir() os.path.isfile() Path.is_file() os.path.islink() Path.is_symlink() os.link() Path.hardlink_to() os.symlink() Path.symlink_to() os.readlink() Path.readlink() os.path.relpath() Path.relative_to()2 os.stat() Path.stat(), Path.owner(), Path.group() os.path.isabs() PurePath.is_absolute() os.path.join() PurePath.joinpath() os.path.basename() PurePath.name os.path.dirname() PurePath.parent os.path.samefile() Path.samefile() os.path.splitext() PurePath.suffix Footnotes 1 os.path.abspath()doesnotresolvesymboliclinkswhilePath.resolve()does. 2 Path.relative_to()requiresselftobethesubpathoftheargument,butos.path.relpath()doesnot. TableofContents pathlib—Object-orientedfilesystempaths Basicuse Purepaths Generalproperties Operators Accessingindividualparts Methodsandproperties Concretepaths Methods Correspondencetotoolsintheosmodule Previoustopic FileandDirectoryAccess Nexttopic os.path—Commonpathnamemanipulations ThisPage ReportaBug ShowSource Navigation index modules| next| previous| Python» 3.10.4Documentation» ThePythonStandardLibrary» FileandDirectoryAccess» pathlib—Object-orientedfilesystempaths | "



請為這篇文章評分?