简体   繁体   English

如何创建特定的文件夹/子文件夹树?

[英]How to create a specific folder/subfolder tree?

I'm trying to create a very specific folder tree using Python that will create predefined folders and subfolders. 我正在尝试使用Python创建一个非常特定的文件夹树,该树将创建预定义的文件夹和子文件夹。 I can create the top and second level folders, but the program messes up when it creates the third and fourth level folders. 我可以创建顶级和第二级文件夹,但是在创建第三级和第四级文件夹时,程序会混乱。 It either doesn't make these folders, or makes them in the incorrect places. 它要么不创建这些文件夹,要么将它们放置在错误的位置。 I'm trying to use os.makedirs and can't figure out an easier way to do it than nested for loops which is messy and probably causing all of the problems. 我正在尝试使用os.makedirs ,并且没有比嵌套for循环更简单的方法了for这很麻烦,可能会导致所有问题。

import os

topLvl=["1", "2", "3"]
docSecLvl=["Info", "Reports"]
findSecLvl=["Ex", "In", "Ph"]
dataSecLvl=["DB", "Ph", "NM", "Test", "Vul", "App"]
phThrdLvl=["Template", "Payload"]
nm_vulsThrdLvl=["Ex", "In"]
ntmFrthLvl=["Nm", "Eye"]
vulsFrthLvl=["NS"]
appThrdLvl=["2", "3"]

def main():
    for dir1 in topLvl:
        if dir1=="1":
            for dir2 in docSecLvl:
                dirmake(dir1, dir2)
        if dir1=="2":
            for dir2 in findSecLvl:
                dirmake(dir1, dir2)
        if dir1=="3":
            for dir2 in dataSecLvl:
                dirmake(dir1, dir2)

            if dir2=="Ph":
                for dir3 in phThrdLvl:
                    dirmake(dir2, dir3)

            if dir2=="NM":
                for dir3 in nm_vulsThrdLvl:
                    dirmake(dir2, dir3)

                if dir3=="Ex":
                    for dir4 in ntmFrthLvl: 
                        dirmake(dir3, dir4)

                if dir3=="In":
                    for dir4 in ntmFrthLvl: 
                        dirmake(dir3, dir4)

            if dir2=="Vul":
                for dir3 in nm_vulsThrdLvl:
                    dirmake(dir2, dir3)

                if dir3=="Ex":
                    for dir4 in vulFrthLvl: 
                        dirmake(dir3, dir4)

                if dir3=="In":
                    for dir4 in vulFrthLvl: 
                        dirmake(dir3, dir4)

            if dir2=="App":
                for dir3 in appThrdLvl:
                    dirmake(dir2, dir3)



    def dirmake(d1, d2):
        try: os.makedirs(os.path.join(d1, d2))
        except OSError: pass

    main()

Well, the foremost problem with the existing code is that it just joins two directory names to make a path, so for instance "App" and "2" is made into the path "App/2" instead of "3/App/2", as it should be. 好了,现有代码的首要问题是,它仅将两个目录名连接在一起以创建路径,因此例如将“ App”和“ 2”设置为路径“ App / 2”而不是“ 3 / App / 2” ”,应该是这样。

Also, using makedirs() is slightly dangerous, as it will make all intermediate directories, even if they are wrong for some reason and don't exist. 另外,使用makedirs()稍微有些危险,因为它将创建所有中间目录,即使它们由于某种原因而错误并且不存在。 And the existing code demonstrates that nicely, as it will make two levels deep of wrong directories without failing. 现有的代码很好地说明了这一点,因为它将使错误目录的深度达到两个级别而不会失败。

I would suggest representing the tree to create with the help of nested dictionaries, like that: 我建议代表在嵌套字典的帮助下创建的树,像这样:

NTM_FOURTH_LEVEL = {
    "Nm": {},
    "Eye": {},
}

VULS_FOURTH_LEVEL = {
    "NS": {},
}

DIRECTORY_STRUCTURE = {
    "1": {
        "Info": {},
        "Reports": {},
    },
    "2": {
        "Ex": {},
        "In": {},
        "Ph": {},
    },
    "3": {
        "DB": {},
        "Ph": {
            "Template": {},
            "Payload": {},
        },
        "NM": {
            "Ex": NTM_FOURTH_LEVEL,
            "In": NTM_FOURTH_LEVEL,
        },
        "Vul": {
            "Ex": VULS_FOURTH_LEVEL,
            "In": VULS_FOURTH_LEVEL,
        },
        "App": {
            "2": {},
            "3": {},
        },
    },
}

And then you can use a small and elegant recursive function to create the actual directory tree: 然后,您可以使用一个小巧优雅的递归函数来创建实际的目录树:

import os
import os.path


def make_dir_tree(tree, prefix=''):
    for name, subtree in tree.items():
        path = os.path.join(prefix, name)
        os.mkdir(path)
        make_dir_tree(subtree, prefix=path)


def main():
    make_dir_tree(DIRECTORY_STRUCTURE)


if __name__ == '__main__':
    main()

As an extra that comes for free, you can use the prefix parameter to create the tree under some directory you specify instead of the current directory: 作为免费提供的一项额外功能,您可以使用prefix参数在您指定的某个目录下而不是当前目录下创建树:

make_dir_tree(DIRECTORY_STRUCTURE, prefix="somewhere/deeper")
make_dir_tree(DIRECTORY_STRUCTURE, prefix="/absolute/path")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM