文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 61.182.251.99 [2004-09-25 01:10:00]

1. 描述

Splitting a Path into All of Its Parts

分解出文件路径所有组成部分

Credit: Trent Mick

1.1. 问题 Problem

You want to process subparts of a file or directory path.

需要处理文件或目录路径的各部分

1.2. 解决 Solution

We can define a function that uses os.path.split to break out all of the parts of a file or directory path:

可以定义一个函数利用os.path.split函数将路径的各部分分解出来:

   1 import os, sys
   2 def splitall(path):
   3     allparts = []
   4     while 1:
   5         parts = os.path.split(path)
   6         if parts[0] == path:  # sentinel for absolute paths  #绝对路径的哨兵
   7             allparts.insert(0, parts[0])
   8             break
   9         elif parts[1] == path: # sentinel for relative paths #相对路径的哨兵
  10             allparts.insert(0, parts[1])
  11             break
  12         else:                                                #处理其余部分 
  13             path = parts[0]
  14             allparts.insert(0, parts[1])
  15     return allparts

1.3. 讨论 Discussion

The os.path.split function splits a path into two parts: everything before the final slash and everything after it. For example:

函数os.path.split将路径分成两部分:以最后的"\"(windows)或者"/"(类Unix)为界,前一部分为头,后一部分为尾。

   >>> os.path.split('c:\\foo\\bar\\baz.txt')
   ('c:\\foo\\bar', 'baz.txt')

Often, it's useful to process parts of a path more generically; for example, if you want to walk up a directory. This recipe splits a path into each piece that corresponds to a mount point, directory name, or file. A few test cases make it clear:

常见的更普通的任务是处理路径的各部分,沿着路径上溯并处理各级路径。上面脚本将路径分解为挂载点、目录名、和(或)文件名的序列。 看看测试结果会清楚些:

>>> 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']

1.4. 参考 See Also

食谱4.17 ; http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d4_2d17

Python 文档os.path 模块部分.

附:

os.path.split( path): Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In nearly all cases, join(head, tail) equals path (the only exception being when there were multiple slashes separating head from tail).