Существует ли метод os для создания диктонары == {"folder": ['' sub_folder "," file1 "," file2 "...]} из определенного каталога? - PullRequest
0 голосов
/ 22 января 2019
class Directory_info:
    directory = None

    def __init__(self, path):
        '''
        Walks Through the predetermined directory and uses built-in os methods to check if item is file or directory
        '''
        directory = path
        item_list = os.listdir(directory) #generates a list of items present in the predetermined directory
        files = []
        dirs = []
        dict={}
        for x in item_list:
            path = os.path.join(directory, x) #yields the path of the current item
            if os.path.isfile(path):          #checks if the current item is a file using it's path
                files.append(x)
            else:
                dirs.append(x)
        print "Files:\n"+str(files)
        print "Directories:\n"+str(dirs)

Этот код генерирует два списка из каталога:
1) Файлы
2) Папки

Мне нужен обходной путь, который даст мне дерево каталогов в формате словаря.

1 Ответ

0 голосов
/ 22 января 2019
import os

def get_directory_structure(rootdir):
    """
    Creates a nested dictionary that represents the folder structure of rootdir
    """
    dir = {}
    rootdir = rootdir.rstrip(os.sep)
    start = rootdir.rfind(os.sep) + 1
    for path, dirs, files in os.walk(rootdir):
        folders = path[start:].split(os.sep)
        subdir = dict.fromkeys(files)
        parent = reduce(dict.get, folders[:-1], dir)
        parent[folders[-1]] = subdir
    return dir

Результат:

{
    "root": {
        "folder2": {
            "item2": None, 
            "item1": None
        }, 
        "folder1": {
            "subfolder1": {
                "item2": None, 
                "item1": None
            }, 
            "subfolder2": {
                "item3": None
            }
        }
    }
}

Источник

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...