Python 为什么os.path.dirname(path)和path.split()会给出不同的结果?
根据os.path.dirname(path)返回通过将path传递给函数split()而返回的对中的第一个元素。但是,当我尝试调用下面的代码时,我得到了另一个结果:Python 为什么os.path.dirname(path)和path.split()会给出不同的结果?,python,string,character,Python,String,Character,根据os.path.dirname(path)返回通过将path传递给函数split()而返回的对中的第一个元素。但是,当我尝试调用下面的代码时,我得到了另一个结果: os.path.dirname('C:/Polygon/id/folder/folder') “C:/Polygon/id/文件夹” ['C:/Polygon/id/folder/folder'] 但是,如果我在行尾添加一个额外的斜杠: os.path.dirname('C:/Polygon/id/folder/folder/'
os.path.dirname('C:/Polygon/id/folder/folder')
“C:/Polygon/id/文件夹”
['C:/Polygon/id/folder/folder']
但是,如果我在行尾添加一个额外的斜杠:
os.path.dirname('C:/Polygon/id/folder/folder/')
'C:/Polygon/id/文件夹/文件夹'
您调用的是
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')
因此,当您拆分字符串中的'/'
时,最后一个元素将变为空字符串,因为最后一个'/'
后面没有任何内容。因此:
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'
如果你说“C:/Polygon/id/folder/whatever”而不是“double folder”,它是否仍然会做同样的事情?@Brent是的,结果将是一样的
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'