Reputation: 110093
If I have the following file:
file = '/Users/david542/Desktop/work.txt'
I can use os.path.basename(file)
to get the file name.
What command would I use to get the directory of the file (i.e., to get "/Users/david542/Desktop") ?
Upvotes: 2
Views: 338
Reputation: 20419
os.path.dirname(file)
will yield directory name.
import os
print(os.path.dirname("c:/windows/try.txt"))
Upvotes: 1
Reputation: 12537
I think you're searching for os.path.dirname
. Otherwise you could use os.path.split
which returns the path and the filename in a tuple.
Upvotes: 0
Reputation: 5320
os.path.dirname(file)
returns the directory of the passed file name. Alternatively, you can use os.path.split(file)
which will give you a tuple containing the directory name and the file name in one call.
Upvotes: 4
Reputation: 56823
>>> os.path.dirname(os.path.realpath('/Users/david542/Desktop/work.txt'))
Upvotes: 4