获取Python中绝对文件路径的目录路径
我想获取文件所在的目录。比如说,文件的完整路径是:
fullpath = "/absolute/path/to/file"
# something like:
os.getdir(fullpath) # if this existed and behaved like I wanted, it would return "/absolute/path/to"
我可以这样做:
dir = '/'.join(fullpath.split('/')[:-1])
但是上面的例子依赖于特定的目录分隔符,看起来不是很好。有没有更好的方法呢?
1 个回答
75
你在找这个:
>>> import os.path
>>> fullpath = '/absolute/path/to/file'
>>> os.path.dirname(fullpath)
'/absolute/path/to'
相关的函数:
>>> os.path.basename(fullpath)
'file'
>>> os.path.split(fullpath)
('/absolute/path/to','file')