os.chdir(os.path.dirname(os.path.abspath(__file__)))
-
1.os.path.dirname()
- os.path.dirname(path)
- Return the directory name of pathname path. This is the first half of the pair returned by split(path).
>>> print os.path.dirname("F:\pc\work\个人中心\分析\1.txt")
F:\pc\work\个人中心
>>> print os.path.dirname("F:\\pc\\work\\个人中心\\分析\\1.txt")
F:\pc\work\个人中心\分析
>>> print os.path.dirname("D:\My Documents\AppScan\1.txt") #不包含中文
D:\My Documents
>>> print os.path.dirname("D:\\My Documents\\AppScan\\1.txt")
D:\My Documents\AppScan
-
help 对 split()的解释为:
- 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).
-
先查到os,发现如下定义:
- os.path is one of the modules posixpath, or ntpath
再查posixpath.py 中如下:
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
help这个str.rfind()为:
- str.rfind(sub[, start[, end]])
- Return the highest index in the string where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure
>>> x="F:\pc\work\个人中心\分析\1.txt"
>>> a=x.rfind("\\")
>>> a=a+1
>>> print x[:a]
F:\pc\work\个人中心\
>>> print x[a:]
分析.txt
ok了,像自己猜测的一样了,str.rfind()返回了最大的匹配位置,而 head, tail = p[:i], p[i:] 的写法就是用这个位置直接分割字符了,但是这个 if head and head != '/'*len(head): 应该是处理head为空,即当前目录的文件,问题是head != '/'*len(head) 是什么呢?[next]
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
没有评论:
发表评论