Python中获取绝对文件路径的目录路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15022854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:08:00  来源:igfitidea点击:

Get the directory path of absolute file path in Python

pythonpath

提问by ddinchev

I want to get the directory where the file resides. For example the full path is:

我想获取文件所在的目录。例如完整路径是:

fullpath = "/absolute/path/to/file"
# something like:
os.getdir(fullpath) # if this existed and behaved like I wanted, it would return "/absolute/path/to"

I could do it like this:

我可以这样做:

dir = '/'.join(fullpath.split('/')[:-1])

But the example above relies on specific directory separator and is not really pretty. Is there a better way?

但是上面的例子依赖于特定的目录分隔符,并不是很漂亮。有没有更好的办法?

采纳答案by isedev

You are looking for this:

你正在寻找这个:

>>> import os.path
>>> fullpath = '/absolute/path/to/file'
>>> os.path.dirname(fullpath)
'/absolute/path/to'

Related functions:

相关功能:

>>> os.path.basename(fullpath)
'file'
>>> os.path.split(fullpath)
('/absolute/path/to','file')