有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
当前回答
print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))
您可以使用它来获取py文件当前位置的父目录。
其他回答
import os.path
os.path.abspath(os.pardir)
Python 3.4
使用pathlib模块。
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
旧的答案
试试这个:
import os
print os.path.abspath(os.path.join(yourpath, os.pardir))
你的路径就是你想要父路径的路径。
os.path.split(os.path.abspath(mydir))[0]
os.path.abspath(os.path.join(somepath, '..'))
观察:
import posixpath
import ntpath
print ntpath.abspath(ntpath.join('C:\\', '..'))
print ntpath.abspath(ntpath.join('C:\\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))
os.path.abspath('D:\Dir1\Dir2\..')
>>> 'D:\Dir1'
所以a。帮助