os.path — Common pathname manipulations — Python 3.10 ...
文章推薦指數: 80 %
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 | "
延伸文章資訊
- 1os.path — Common pathname manipulations — Python 3.10 ...
path module is always the path module suitable for the operating system Python is running on, and...
- 2Python 獲取文件路徑及文件目錄( __file__ 的使用方法) - GitHub
透過問答,了解世界。Python 的世界. Contribute to dokelung/Python-QA development by creating an account on GitHub.
- 3Python 列出目錄中所有檔案教學:os.listdir 與os.walk - GT Wang
這裡介紹如何在Python 中列出目錄中的檔案,並且配合各種篩選方式,取得符合 ... #!/usr/bin/python # -*- coding: utf-8 -*- from os imp...
- 4Python 取出目錄的路徑dirname
本篇ShengYu 介紹Python 取出目錄的路徑os.path.dirname() 的用法與範例,並示範在linux、macOS、windows 各平台下的差異。以下範例是在Python 3...
- 5dirpath python Code Example - Grepper
Python answers related to “dirpath python”. get path to file without filename python · pathlib pa...