![](/img/trans.png)
[英]Is there a way to get an absolute path of a file which is not in the current working directory (in 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.