Find directory of a file in Python
If I have the following file:
file = '/Users/d开发者_运维百科avid542/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") ?
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.
>>> os.path.dirname(os.path.realpath('/Users/david542/Desktop/work.txt'))
os.path.dirname(file)
will yield directory name.
import os
print(os.path.dirname("c:/windows/try.txt"))
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.
精彩评论