Splitting a Path into All of Its Parts - Python Cookbook [Book]

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

We can define a function that uses os.path.split to break out all of the parts of a file or directory path: import os, sys def splitall(path): allparts ... Skiptomaincontent Prev UpdatingaRandom-AccessFile PythonCookbookby Next TreatingPathnamesasObjects GetfullaccesstoPythonCookbookand60K+othertitles,withfree10-daytrialofO'Reilly. There'salsoliveonlineevents,interactivecontent,certificationprepmaterials,andmore. Startyourfreetrial SplittingaPathintoAllofItsPartsCredit:TrentMickProblemYouwanttoprocesssubpartsofafile ordirectorypath. SolutionWecandefineafunctionthatuses os.path.split tobreakoutallofthepartsofafileordirectorypath: importos,sys defsplitall(path): allparts=[] while1: parts=os.path.split(path) ifparts[0]==path:#sentinelforabsolutepaths allparts.insert(0,parts[0]) break elifparts[1]==path:#sentinelforrelativepaths allparts.insert(0,parts[1]) break else: path=parts[0] allparts.insert(0,parts[1]) returnallpartsDiscussionTheos.path.splitfunctionsplitsapathintotwo parts:everythingbeforethefinalslashandeverythingafterit.For example: >>>os.path.split('c:\\foo\\bar\\baz.txt') ('c:\\foo\\bar','baz.txt')Often,it’susefultoprocesspartsofapathmore generically;forexample,ifyouwanttowalkupadirectory.This recipesplitsapathintoeachpiecethatcorrespondstoamount point,directoryname,orfile.Afewtestcasesmakeitclear: >>>splitall('a/b/c') ['a','b','c'] >>>splitall('/a/b/c/') ['/','a','b','c',''] >>>splitall('/') ['/'] >>>splitall('C:') ['C:'] >>>splitall('C:\\') ['C:\\'] >>>splitall('C:\\a') ['C:\\','a'] >>>splitall('C:\\a\\') ['C:\\','a',''] >>>splitall('C:\\a\\b') ['C:\\','a','b'] >>>splitall('a\\b') ['a','b']SeeAlsoRecipe4.17;documentationonthe os.pathmoduleintheLibraryReference. GetPythonCookbooknowwiththeO’Reillylearningplatform. O’Reillymembersexperienceliveonlinetraining,plusbooks,videos,anddigitalcontentfromnearly200publishers. Startyourfreetrial Don’tleaveempty-handed GetMarkRichards’sSoftwareArchitecturePatternsebooktobetterunderstandhowtodesigncomponents—andhowtheyshouldinteract. It’syours,free. Getitnow Close



請為這篇文章評分?