Kirill Dolmatov
Kirill Dolmatov

Reputation: 327

Why os.path.dirname(path) and path.split() gives different results?

According to official documentation os.path.dirname(path) returns first element of the pair returned by passing path to the function split(). But, when I try to call code below, I get another result:

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

'C:/Polygon/id/folder'

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

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

But, if I add one extra slash to the end of line:

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

'C:/Polygon/id/folder/folder'

Upvotes: 0

Views: 1009

Answers (1)

r.ook
r.ook

Reputation: 13848

You're calling the str.split() method instead of os.path.split(), which instead of splitting with the os.path.sep delimiter, is splitting the whitespace (which there are none in your string, hence, no splits).

Observer the differences:

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']

To answer your other question: the os.path.split() is basically the same as follows:

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

So when you split() the '/' in the string, the last element becomes an empty string because nothing follows the last '/'. Hence:

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'

Upvotes: 1

Related Questions