繁体   English   中英

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

[英]Get the directory path of absolute file path in 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM