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

Contents

1. 描述

# 描述

Splitting a Path into All of Its Parts

Credit: Trent Mick

## 问题 Problem

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

## 解决 Solution

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

   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


## 讨论 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('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']

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).

PyCkBk-4-16 (last edited 2009-12-25 07:09:07 by localhost)

• Page.execute = 1.763s
• getACL = 0.426s
• init = 0.020s