Splitting a Path into All of Its Parts - Python Cookbook [Book]
文章推薦指數: 80 %
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
延伸文章資訊
- 1python split(), os.path.split()和os.path.splitext()函数 - CSDN博客
1. split(). split() 函数通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔num 个子字符串 · 2. os.path.split() · 3. os.pat...
- 2Splitting a Path into All of Its Parts - Python Cookbook [Book]
We can define a function that uses os.path.split to break out all of the parts of a file or direc...
- 3Python os.path.split() Function with Example - AppDividend
The os.path.split() is an inbuilt Python method used to Split the pathname into a pair head and t...
- 4Python | os.path.split() method - GeeksforGeeks
- 5Python os.path.split()用法及代碼示例- 純淨天空
os.path.split() Python中的方法用於將路徑名稱拆分為一對頭部和尾部。 ... Python program to explain os.path.split() method...