在Python中获取绝对文件路径的目录路径
问题描述:
我想获取文件所在的目录。例如,完整路径是:在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])
但上面的例子中依赖于特定的目录分隔符,而不是真的很漂亮。有没有更好的办法?
答
您正在寻找这样的:
>>> 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')
http://docs.python.org/2/library/os.path.html#os.path。目录名 – 2013-02-22 11:58:40