有人能告诉我如何以跨平台的方式在Python中获取路径的父目录。例如C:\Program Files ---> C:\和C:\ ---> C:\如果目录没有父目录,则返回目录本身。问题可能看似简单,但我无法通过谷歌进行挖掘。
3 回答

慕的地8271018
TA贡献1796条经验 获得超4个赞
从Python 3.4更新
使用该pathlib模块。
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent)
老答案
尝试这个:
import os.path
print os.path.abspath(os.path.join(yourpath, os.pardir))
yourpath您想要父母的路径在哪里。

SMILET
TA贡献1796条经验 获得超4个赞
使用os.path.dirname:
>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>
警告:os.path.dirname()根据路径中是否包含尾部斜杠,给出不同的结果。这可能是也可能不是您想要的语义。参看 @kender的答案使用os.path.join(yourpath, os.pardir)。
添加回答
举报
0/150
提交
取消