Reputation: 415
I have recently read about dirname
and basename
. My book uses the following image to explain the difference between them:
I am currently using OSX so my root folder will be /. I wrote the following code in my shell:
path='\\Users\\apple\\Documents\\list.txt'
os.path.dirname(path)
The result that I got was: ''
Then I wrote the following code to check the basename:
os.path.basename(path)
and the result that I got this time was: '\\Users\\apple\\Documents\\list.txt
!
Whats happening over here? How to fix it?
Also, I don't have any text file whose name is list. Shouldn't this cause an error when I was trying to find the dirname
and basename
of a file that does not exist!?
Upvotes: 1
Views: 1738
Reputation: 3570
OSX, just like Linux, uses /
as a separator. You can get the standard separator for your OS from os.path.sep
.
>>> import os
>>> os.path.sep
'/'
>>> path='/Users/apple/Documents/list.txt'
>>> os.path.dirname(path)
'/Users/apple/Documents'
>>> os.path.basename(path)
'list.txt'
Notice that os.path
is just constructing "correct" paths, it does not do any checking, if files exist. That would not make much sense, if you constructed a path to create a new file. You could use os.path.exists()
for that.
Upvotes: 2