我用下面的方法。
(a)由os spearator分割文件的完整路径。
(b)获取结果数组并返回索引范围为[0:lastIndex-1]的elments
-简言之,从拆分后的数组中删除最后一个元素
(c)只需再次使用os分隔符将一个elment short的数组连接在一起。
应该适用于windows和linux。
下面是一个类函数的例子。# @param
# absolutePathToFile an absolute path pointing to a file or directory
# @return
# The path to the parent element of the path (e.g. if the absolutePathToFile represents a file, the result is its parent directory)
# if the path represent a directory, the result is its parent directory
def getParentDirectoryFromFile(self, absolutePathToFile):
splitResutsFromZeroToNMinus1 = absolutePathToFile.split(os.sep)[:-1]
return os.sep.join(splitResutsFromZeroToNMinus1)
pass