为什么os.path.dirname(path)和path.split()给出不同的结果?

时间:2018-11-07 15:42:22

标签: python string character

根据official documentation,os.path.dirname(path)返回路径中的第一个元素,该元素是通过将路径传递给函数split()返回的。但是,当我尝试调用下面的代码时,又得到了另一个结果:

os.path.dirname('C:/Polygon/id/folder/folder')
  

'C:/多边形/ id /文件夹'

'C:/Polygon/id/folder/folder'.split()
  

['C:/ Polygon / id / folder / folder']

但是,如果我在行尾添加一个额外的斜杠:

os.path.dirname('C:/Polygon/id/folder/folder/')
  

'C:/多边形/ id /文件夹/文件夹'

1 个答案:

答案 0 :(得分:1)

您正在调用str.split()而不是os.path.split()的方法,而不是使用os.path.sep分隔符进行拆分,而是在拆分空格(因此,字符串中没有空格),没有分裂)。

观察差异:

p = 'C:/Polygon/id/folder/folder'

os.path.dirname(p)    # dirname method of os.path
# 'C:/Polygon/id/folder'

os.path.split(p)      # split method of os.path
#('C:/Polygon/id/folder', 'folder')

p.split()             # split method of str object with space
# ['C:/Polygon/id/folder/folder']

p.split('/')          # split method of str object with '/'      
# ['C:', 'Polygon', 'id', 'folder', 'folder']

要回答另一个问题:os.path.split()基本上与以下内容相同:

('/'.join(p.split('/')[:-1]), p.split('/')[-1])
# i.e. tuple of (everything but the last element, the last element)
# ('C:/Polygon/id/folder', 'folder')

因此,当您在字符串中split() '/'时,最后一个元素将变为空字符串,因为在最后一个'/'之后没有任何内容。因此:

os.path.split(p)          
# ('C:/Polygon/id/folder/folder', '')

('/'.join(p.split('/')[:-1]), p.split('/')[-1]) 
# ('C:/Polygon/id/folder/folder', '')

os.path.dirname(p)      
# since it returns the first element of os.path.split():
# 'C:/Polygon/id/folder/folder'