有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
当前回答
上面给出的答案对于上升到一个或两个目录级别都非常合适,但是如果需要遍历目录树的许多级别(例如,5或10级),它们可能会有点麻烦。这可以通过加入一个N个os的列表来简单地完成。os.path.join中的Pardirs。例子:
import os
# Create list of ".." times 5
upup = [os.pardir]*5
# Extract list as arguments of join()
go_upup = os.path.join(*upup)
# Get abspath for current file
up_dir = os.path.abspath(os.path.join(__file__, go_upup))
其他回答
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 "------------------------------------------------------------"
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
>>> os.path.basename(os.path.dirname(<your_path>))
例如在Ubuntu中:
>>> my_path = '/home/user/documents'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'user'
例如在Windows中:
>>> my_path = 'C:\WINDOWS\system32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'
这两个例子都是在Python 2.7中尝试的
print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))
您可以使用它来获取py文件当前位置的父目录。
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', '..'))