Python:根据Dictionary键名创建文件目录

时间:2014-02-27 02:45:56

标签: python

我想知道是否有办法将字典转换为目录结构。例如,带有以下键的字典:

dict['dir1']['subdir1']['subsubdir']['folder1']
            ['subdir2']['subsubdir']['folder1']['folder2']['folder3']
            ['subdir3']['subsubdir']

将导致三个目录(其中每个子目录对应于字典键名称:

/dir1/subdir1/subsubdir/folder1/
/dir1/subdir2/subsubdir/folder1/folder2/folder3/
/dir1/subdir3/subsubdir/

3 个答案:

答案 0 :(得分:3)

使用快速递归函数非常简单:

nested = {'folderA': {'sub1': None, 'sub2': {'subsub1': None}},
          'folderB': {'sub1': None}}

def make_dirs_from_dict(d, current_dir='./'):
    for key, val in d.items():
        os.mkdir(os.path.join(current_dir, key))
        if type(val) == dict:
            make_dirs_from_dict(val, os.path.join(current_dir, key))

make_dirs_from_dict(nested)

此解决方案在遇到非dict值时会停止,但您可以对其进行调整,以使端点为(可能为空)列表。

结果:

C:\Users\me\dirplay>tree
start_dir.
├───folderA
│   ├───sub1
│   └───sub2
│       └───subsub1
└───folderB
    └───sub1

答案 1 :(得分:3)

from collections import defaultdict
import os
import os.path

def tree():
    return defaultdict(tree)
d = tree()

d["dir1"]["subdir1"]["subsubdir"]["folder1"]
d["dir1"]["subdir2"]["subsubdir"]["folder1"]["folder2"]["folder3"]
d["dir1"]["subdir3"]["subsubdir"]

def rec(directory, current_path):
    if len(directory):
        for direc in directory:
            rec(directory[direc], os.path.join(current_path, direc))
    else:
        os.makedirs(current_path)

rec(d, "")

<强>输出

~/Desktop$ tree dir1
dir1
|-- subdir1
|   `-- subsubdir
|       `-- folder1
|-- subdir2
|   `-- subsubdir
|       `-- folder1
|           `-- folder2
|               `-- folder3
`-- subdir3
    `-- subsubdir

10 directories, 0 files

答案 2 :(得分:2)

我并不完全遵循您的语法,但您可以使用元组列表

import os   
dirs = [(dir1,dir2,dir3), (dir1,dir2,dir4,dir5),...]
    for dir in dirs:
         loc = os.path.join(*dir)
         if not os.path.exists(loc):
               os.makedirs(loc)

可能需要一些调整,但应该这样做。