Python 2.7 如何在Python中获取父目录并将其放入列表中

Python 2.7 如何在Python中获取父目录并将其放入列表中,python-2.7,recursion,filepath,subdirectory,Python 2.7,Recursion,Filepath,Subdirectory,Python中是否有任何方法可以获取父目录并将它们存储在列表中 假设我有一个文件路径(dir1/dir2/dir3/dir4),我想要的是删除dir4,并将其添加到我的列表中,删除dir3,然后再次添加(类似递归) 以下是我到目前为止的情况。我知道如何切片文件路径(叶目录),但我不知道如何将切片的文件路径存储到列表中 Mylist =[] # return file path of the parent (e.g: dir1/dir2/dir3 ==> dir1/dir2) def g

Python中是否有任何方法可以获取父目录并将它们存储在列表中

假设我有一个文件路径(
dir1/dir2/dir3/dir4
),我想要的是删除
dir4
,并将其添加到我的列表中,删除
dir3
,然后再次添加(类似递归)

以下是我到目前为止的情况。我知道如何切片文件路径(叶目录),但我不知道如何将切片的文件路径存储到列表中

Mylist =[]

# return file path of the parent (e.g: dir1/dir2/dir3  ==> dir1/dir2)
def getParentpath(path):
    return "/".join(path.split("/")[:-1])

def checkParentsAndCreate(filepath):
    if not repository.exists(filepath): # check the path is already there?
        checkParentsAndCreate(getParent(filepath)) 
        try:
            repository.create(factory.configurationItem( filepath,'core.Directory'))
        except:
            print 'Unable to create Folder ', filepath
    else:
        # file path is exist, 
        # Need to create folder/path(that I sliced, items in Mylist, in order)...

我对你的问题有点困惑。您是否希望拆分路径并将所有部分添加到列表中?因此最终目标是创建整个目录链?您可以使用
os.makedirs(filepath)
import os
首先-在文件开头)。@CristiFati,谢谢您的评论。老实说,我不能使用os.makedirs函数,因为我正在创建的文件夹位于服务器上,所以我需要使用repository.create()来创建文件夹。@Bharel,谢谢您提供的信息。对不起,我的英语不好。是的,这就是我想要做的:拆分路径并将所有路径逐个添加到列表中),以便以后在服务器中按顺序重新创建文件夹。所以,我只是想知道你是否知道如何解决这个问题?提前谢谢。