有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
当前回答
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(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', '..'))
import os
def parent_filedir(n):
return parent_filedir_iter(n, os.path.dirname(__file__))
def parent_filedir_iter(n, path):
n = int(n)
if n <= 1:
return path
return parent_filedir_iter(n - 1, os.path.dirname(path))
test_dir = os.path.abspath(parent_filedir(2))
import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"
获取父目录路径并创建新目录(名称为new_dir)
获取父目录路径
os.path.abspath('..')
os.pardir
示例1
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))
示例2
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))
使用os.path.dirname:
>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>
注意:os.path.dirname()会给出不同的结果,这取决于路径中是否包含后面的斜杠。这可能是也可能不是您想要的语义。Cf. @kender的答案使用os.path。加入(yourpath os.pardir)。