|

楼主 |
发表于 2006-10-19 07:44:13
|
显示全部楼层
贴一下纯 python 的,
pandazxx 改成 C 就是。
- ## 是否 / 开头
- def isabs(s):
- """Test whether a path is absolute"""
- return s.startswith('/')
- ## 连接路径
- def join(a, *p):
- """Join two or more pathname components, inserting '/' as needed"""
- path = a
- for b in p:
- if b.startswith('/'):
- path = b
- elif path == '' or path.endswith('/'):
- path += b
- else:
- path += '/' + b
- return path
- ## 分割路径
- def split(p):
- """Split a pathname. Returns tuple "(head, tail)" where "tail" is
- everything after the final slash. Either part may be empty."""
- i = p.rfind('/') + 1
- head, tail = p[:i], p[i:]
- if head and head != '/'*len(head):
- head = head.rstrip('/')
- return head, tail
- ## 去掉 // , /./ , /../ 之类
- def normpath(path):
- """Normalize path, eliminating double slashes, etc."""
- if path == '':
- return '.'
- initial_slashes = path.startswith('/')
- # POSIX allows one or two initial slashes, but treats three or more
- # as single slash.
- if (initial_slashes and
- path.startswith('//') and not path.startswith('///')):
- initial_slashes = 2
- comps = path.split('/')
- new_comps = []
- for comp in comps:
- if comp in ('', '.'):
- continue
- if (comp != '..' or (not initial_slashes and not new_comps) or
- (new_comps and new_comps[-1] == '..')):
- new_comps.append(comp)
- elif new_comps:
- new_comps.pop()
- comps = new_comps
- path = '/'.join(comps)
- if initial_slashes:
- path = '/'*initial_slashes + path
- return path or '.'
- ## 绝对路径
- def abspath(path):
- """Return an absolute path."""
- if not isabs(path):
- path = join(os.getcwd(), path)
- return normpath(path)
复制代码 |
|