os.path — Common pathname manipulations — Python 3.10 ...

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

path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import ... Navigation index modules| next| previous| Python» 3.10.4Documentation» ThePythonStandardLibrary» FileandDirectoryAccess» os.path—Commonpathnamemanipulations | os.path—Commonpathnamemanipulations¶ Sourcecode:Lib/posixpath.py(forPOSIX)and Lib/ntpath.py(forWindowsNT). Thismoduleimplementssomeusefulfunctionsonpathnames.Toreadorwrite filesseeopen(),andforaccessingthefilesystemseetheos module.Thepathparameterscanbepassedasstrings,orbytes,oranyobject implementingtheos.PathLikeprotocol. Unlikeaunixshell,Pythondoesnotdoanyautomaticpathexpansions. Functionssuchasexpanduser()andexpandvars()canbeinvoked explicitlywhenanapplicationdesiresshell-likepathexpansion.(Seealso theglobmodule.) Seealso Thepathlibmoduleoffershigh-levelpathobjects. Note Allofthesefunctionsaccepteitheronlybytesoronlystringobjectsas theirparameters.Theresultisanobjectofthesametype,ifapathor filenameisreturned. Note Sincedifferentoperatingsystemshavedifferentpathnameconventions,there areseveralversionsofthismoduleinthestandardlibrary.The os.pathmoduleisalwaysthepathmodulesuitablefortheoperating systemPythonisrunningon,andthereforeusableforlocalpaths.However, youcanalsoimportandusetheindividualmodulesifyouwanttomanipulate apaththatisalwaysinoneofthedifferentformats.Theyallhavethe sameinterface: posixpathforUNIX-stylepaths ntpathforWindowspaths Changedinversion3.8:exists(),lexists(),isdir(),isfile(), islink(),andismount()nowreturnFalseinsteadof raisinganexceptionforpathsthatcontaincharactersorbytes unrepresentableattheOSlevel. os.path.abspath(path)¶ Returnanormalizedabsolutizedversionofthepathnamepath.Onmost platforms,thisisequivalenttocallingthefunctionnormpath()as follows:normpath(join(os.getcwd(),path)). Changedinversion3.6:Acceptsapath-likeobject. os.path.basename(path)¶ Returnthebasenameofpathnamepath.Thisisthesecondelementofthe pairreturnedbypassingpathtothefunctionsplit().Notethat theresultofthisfunctionisdifferent fromtheUnixbasenameprogram;wherebasenamefor '/foo/bar/'returns'bar',thebasename()functionreturnsan emptystring(''). Changedinversion3.6:Acceptsapath-likeobject. os.path.commonpath(paths)¶ Returnthelongestcommonsub-pathofeachpathnameinthesequence paths.RaiseValueErrorifpathscontainbothabsolute andrelativepathnames,thepathsareonthedifferentdrivesor ifpathsisempty.Unlikecommonprefix(),thisreturnsa validpath. Availability:Unix,Windows. Newinversion3.5. Changedinversion3.6:Acceptsasequenceofpath-likeobjects. os.path.commonprefix(list)¶ Returnthelongestpathprefix(takencharacter-by-character)thatisa prefixofallpathsinlist.Iflistisempty,returntheemptystring (''). Note Thisfunctionmayreturninvalidpathsbecauseitworksa characteratatime.Toobtainavalidpath,see commonpath(). >>>os.path.commonprefix(['/usr/lib','/usr/local/lib']) '/usr/l' >>>os.path.commonpath(['/usr/lib','/usr/local/lib']) '/usr' Changedinversion3.6:Acceptsapath-likeobject. os.path.dirname(path)¶ Returnthedirectorynameofpathnamepath.Thisisthefirstelementof thepairreturnedbypassingpathtothefunctionsplit(). Changedinversion3.6:Acceptsapath-likeobject. os.path.exists(path)¶ ReturnTrueifpathreferstoanexistingpathoranopen filedescriptor.ReturnsFalseforbrokensymboliclinks.On someplatforms,thisfunctionmayreturnFalseifpermissionis notgrantedtoexecuteos.stat()ontherequestedfile,even ifthepathphysicallyexists. Changedinversion3.3:pathcannowbeaninteger:Trueisreturnedifitisan openfiledescriptor,Falseotherwise. Changedinversion3.6:Acceptsapath-likeobject. os.path.lexists(path)¶ ReturnTrueifpathreferstoanexistingpath.ReturnsTruefor brokensymboliclinks.Equivalenttoexists()onplatformslacking os.lstat(). Changedinversion3.6:Acceptsapath-likeobject. os.path.expanduser(path)¶ OnUnixandWindows,returntheargumentwithaninitialcomponentof~or ~userreplacedbythatuser’shomedirectory. OnUnix,aninitial~isreplacedbytheenvironmentvariableHOME ifitisset;otherwisethecurrentuser’shomedirectoryislookedupinthe passworddirectorythroughthebuilt-inmodulepwd.Aninitial~user islookedupdirectlyinthepassworddirectory. OnWindows,USERPROFILEwillbeusedifset,otherwiseacombination ofHOMEPATHandHOMEDRIVEwillbeused.Aninitial ~userishandledbycheckingthatthelastdirectorycomponentofthecurrent user’shomedirectorymatchesUSERNAME,andreplacingitifso. Iftheexpansionfailsorifthepathdoesnotbeginwithatilde,thepathis returnedunchanged. Changedinversion3.6:Acceptsapath-likeobject. Changedinversion3.8:NolongerusesHOMEonWindows. os.path.expandvars(path)¶ Returntheargumentwithenvironmentvariablesexpanded.Substringsoftheform $nameor${name}arereplacedbythevalueofenvironmentvariable name.Malformedvariablenamesandreferencestonon-existingvariablesare leftunchanged. OnWindows,%name%expansionsaresupportedinadditionto$nameand ${name}. Changedinversion3.6:Acceptsapath-likeobject. os.path.getatime(path)¶ Returnthetimeoflastaccessofpath.Thereturnvalueisafloatingpointnumbergiving thenumberofsecondssincetheepoch(seethetimemodule).Raise OSErrorifthefiledoesnotexistorisinaccessible. os.path.getmtime(path)¶ Returnthetimeoflastmodificationofpath.Thereturnvalueisafloatingpointnumber givingthenumberofsecondssincetheepoch(seethetimemodule). RaiseOSErrorifthefiledoesnotexistorisinaccessible. Changedinversion3.6:Acceptsapath-likeobject. os.path.getctime(path)¶ Returnthesystem’sctimewhich,onsomesystems(likeUnix)isthetimeofthe lastmetadatachange,and,onothers(likeWindows),isthecreationtimeforpath. Thereturnvalueisanumbergivingthenumberofsecondssincetheepoch(see thetimemodule).RaiseOSErrorifthefiledoesnotexistor isinaccessible. Changedinversion3.6:Acceptsapath-likeobject. os.path.getsize(path)¶ Returnthesize,inbytes,ofpath.RaiseOSErrorifthefiledoes notexistorisinaccessible. Changedinversion3.6:Acceptsapath-likeobject. os.path.isabs(path)¶ ReturnTrueifpathisanabsolutepathname.OnUnix,thatmeansit beginswithaslash,onWindowsthatitbeginswitha(back)slashafterchopping offapotentialdriveletter. Changedinversion3.6:Acceptsapath-likeobject. os.path.isfile(path)¶ ReturnTrueifpathisanexistingregularfile. Thisfollowssymboliclinks,sobothislink()andisfile()can betrueforthesamepath. Changedinversion3.6:Acceptsapath-likeobject. os.path.isdir(path)¶ ReturnTrueifpathisanexistingdirectory.This followssymboliclinks,sobothislink()andisdir()canbetrue forthesamepath. Changedinversion3.6:Acceptsapath-likeobject. os.path.islink(path)¶ ReturnTrueifpathreferstoanexistingdirectory entrythatisasymboliclink.AlwaysFalseifsymboliclinksarenot supportedbythePythonruntime. Changedinversion3.6:Acceptsapath-likeobject. os.path.ismount(path)¶ ReturnTrueifpathnamepathisamountpoint:apointina filesystemwhereadifferentfilesystemhasbeenmounted.OnPOSIX,the functioncheckswhetherpath’sparent,path/..,isonadifferent devicethanpath,orwhetherpath/..andpathpointtothesame i-nodeonthesamedevice—thisshoulddetectmountpointsforallUnix andPOSIXvariants.Itisnotabletoreliablydetectbindmountsonthe samefilesystem.OnWindows,adriveletterrootandashareUNCare alwaysmountpoints,andforanyotherpathGetVolumePathNameiscalled toseeifitisdifferentfromtheinputpath. Newinversion3.4:Supportfordetectingnon-rootmountpointsonWindows. Changedinversion3.6:Acceptsapath-likeobject. os.path.join(path,*paths)¶ Joinoneormorepathcomponentsintelligently.Thereturnvalueisthe concatenationofpathandanymembersof*pathswithexactlyone directoryseparatorfollowingeachnon-emptypartexceptthelast,meaning thattheresultwillonlyendinaseparatorifthelastpartisempty.If acomponentisanabsolutepath,allpreviouscomponentsarethrownaway andjoiningcontinuesfromtheabsolutepathcomponent. OnWindows,thedriveletterisnotresetwhenanabsolutepathcomponent (e.g.,r'\foo')isencountered.Ifacomponentcontainsadrive letter,allpreviouscomponentsarethrownawayandthedriveletteris reset.Notethatsincethereisacurrentdirectoryforeachdrive, os.path.join("c:","foo")representsapathrelativetothecurrent directoryondriveC:(c:foo),notc:\foo. Changedinversion3.6:Acceptsapath-likeobjectforpathandpaths. os.path.normcase(path)¶ Normalizethecaseofapathname.OnWindows,convertallcharactersinthe pathnametolowercase,andalsoconvertforwardslashestobackwardslashes. Onotheroperatingsystems,returnthepathunchanged. Changedinversion3.6:Acceptsapath-likeobject. os.path.normpath(path)¶ Normalizeapathnamebycollapsingredundantseparatorsandup-level referencessothatA//B,A/B/,A/./BandA/foo/../Ball becomeA/B.Thisstringmanipulationmaychangethemeaningofapath thatcontainssymboliclinks.OnWindows,itconvertsforwardslashesto backwardslashes.Tonormalizecase,usenormcase(). Note OnPOSIXsystems,inaccordancewithIEEEStd1003.12013Edition;4.13 PathnameResolution, ifapathnamebeginswithexactlytwoslashes,thefirstcomponent followingtheleadingcharactersmaybeinterpretedinanimplementation-defined manner,althoughmorethantwoleadingcharactersshallbetreatedasa singlecharacter. Changedinversion3.6:Acceptsapath-likeobject. os.path.realpath(path,*,strict=False)¶ Returnthecanonicalpathofthespecifiedfilename,eliminatinganysymbolic linksencounteredinthepath(iftheyaresupportedbytheoperating system). Ifapathdoesn’texistorasymlinkloopisencountered,andstrictis True,OSErrorisraised.IfstrictisFalse,thepathis resolvedasfaraspossibleandanyremainderisappendedwithoutchecking whetheritexists. Note Thisfunctionemulatestheoperatingsystem’sprocedureformakingapath canonical,whichdiffersslightlybetweenWindowsandUNIXwithrespect tohowlinksandsubsequentpathcomponentsinteract. OperatingsystemAPIsmakepathscanonicalasneeded,soit’snot normallynecessarytocallthisfunction. Changedinversion3.6:Acceptsapath-likeobject. Changedinversion3.8:SymboliclinksandjunctionsarenowresolvedonWindows. Changedinversion3.10:Thestrictparameterwasadded. os.path.relpath(path,start=os.curdir)¶ Returnarelativefilepathtopatheitherfromthecurrentdirectoryor fromanoptionalstartdirectory.Thisisapathcomputation:the filesystemisnotaccessedtoconfirmtheexistenceornatureofpathor start.OnWindows,ValueErrorisraisedwhenpathandstart areondifferentdrives. startdefaultstoos.curdir. Availability:Unix,Windows. Changedinversion3.6:Acceptsapath-likeobject. os.path.samefile(path1,path2)¶ ReturnTrueifbothpathnameargumentsrefertothesamefileordirectory. Thisisdeterminedbythedevicenumberandi-nodenumberandraisesan exceptionifanos.stat()calloneitherpathnamefails. Availability:Unix,Windows. Changedinversion3.2:AddedWindowssupport. Changedinversion3.4:Windowsnowusesthesameimplementationasallotherplatforms. Changedinversion3.6:Acceptsapath-likeobject. os.path.sameopenfile(fp1,fp2)¶ ReturnTrueifthefiledescriptorsfp1andfp2refertothesamefile. Availability:Unix,Windows. Changedinversion3.2:AddedWindowssupport. Changedinversion3.6:Acceptsapath-likeobject. os.path.samestat(stat1,stat2)¶ ReturnTrueifthestattuplesstat1andstat2refertothesamefile. Thesestructuresmayhavebeenreturnedbyos.fstat(), os.lstat(),oros.stat().Thisfunctionimplementsthe underlyingcomparisonusedbysamefile()andsameopenfile(). Availability:Unix,Windows. Changedinversion3.4:AddedWindowssupport. Changedinversion3.6:Acceptsapath-likeobject. os.path.split(path)¶ Splitthepathnamepathintoapair,(head,tail)wheretailisthe lastpathnamecomponentandheadiseverythingleadinguptothat.The tailpartwillnevercontainaslash;ifpathendsinaslash,tail willbeempty.Ifthereisnoslashinpath,headwillbeempty.If pathisempty,bothheadandtailareempty.Trailingslashesare strippedfromheadunlessitistheroot(oneormoreslashesonly).In allcases,join(head,tail)returnsapathtothesamelocationaspath (butthestringsmaydiffer).Alsoseethefunctionsdirname()and basename(). Changedinversion3.6:Acceptsapath-likeobject. os.path.splitdrive(path)¶ Splitthepathnamepathintoapair(drive,tail)wheredriveiseither amountpointortheemptystring.Onsystemswhichdonotusedrive specifications,drivewillalwaysbetheemptystring.Inallcases,drive +tailwillbethesameaspath. OnWindows,splitsapathnameintodrive/UNCsharepointandrelativepath. Ifthepathcontainsadriveletter,drivewillcontaineverything uptoandincludingthecolon: >>>splitdrive("c:/dir") ("c:","/dir") IfthepathcontainsaUNCpath,drivewillcontainthehostname andshare,uptobutnotincludingthefourthseparator: >>>splitdrive("//host/computer/dir") ("//host/computer","/dir") Changedinversion3.6:Acceptsapath-likeobject. os.path.splitext(path)¶ Splitthepathnamepathintoapair(root,ext)suchthatroot+ext== path,andtheextension,ext,isemptyorbeginswithaperiodandcontainsat mostoneperiod. Ifthepathcontainsnoextension,extwillbe'': >>>splitext('bar') ('bar','') Ifthepathcontainsanextension,thenextwillbesettothisextension, includingtheleadingperiod.Notethatpreviousperiodswillbeignored: >>>splitext('foo.bar.exe') ('foo.bar','.exe') >>>splitext('/foo/bar.exe') ('/foo/bar','.exe') Leadingperiodsofthelastcomponentofthepathareconsideredto bepartoftheroot: >>>splitext('.cshrc') ('.cshrc','') >>>splitext('/foo/....jpg') ('/foo/....jpg','') Changedinversion3.6:Acceptsapath-likeobject. os.path.supports_unicode_filenames¶ TrueifarbitraryUnicodestringscanbeusedasfilenames(withinlimitations imposedbythefilesystem). Previoustopic pathlib—Object-orientedfilesystempaths Nexttopic fileinput—Iterateoverlinesfrommultipleinputstreams ThisPage ReportaBug ShowSource Navigation index modules| next| previous| Python» 3.10.4Documentation» ThePythonStandardLibrary» FileandDirectoryAccess» os.path—Commonpathnamemanipulations | "



請為這篇文章評分?