Skip to content Skip to sidebar Skip to footer

Dictionary Of Folders And Subfolders

I need to make function, which will return for a given folder, a Dictionary, which describes its content. Keys let be the names of the subfolders and files, key value representing

Solution 1:

def f(path):
    if os.path.isdir(path):
        d = {}
        for name in os.listdir(path):
            d[name] = f(os.path.join(path, name))
    else:
        d = os.path.getsize(path)
    return d

Solution 2:

def dumps(d, level=0, indent=4):
    if isinstance(d, dict):
        if not d: return '{}'
        return '{\n' + ',\n'.join(
            (' ' * (level+indent) + "'{}' : {}".format(name, dumps(d[name], level+indent, indent)) for name in d),
        ) + '\n' + ' ' * level + '}'
    else:
        return str(d)

print dumps({
   'delo' : {
      'navodila.docx' : 83273,
      'porocilo.pdf' : 37653347,
      'artikli.dat' : 253
   },
   'igre' : {},
   'seznam.txt' : 7632,
   'razno' : {
      'slika.jpg' : 4275,
      'prijatelji' : {
         'janez.jpg' : 8734765,
         'mojca.png' : 8736,
         'veronika.jpg' : 8376535,
         'miha.gif' : 73645
      },
      'avto.xlsx' : 76357
   },
   'ocene.xlsx' : 8304
})

Solution 3:

import os

def get_listings(directory):
    parent, folder = os.path.split(directory)
    listings = {
        'folder': folder,
        'children-files': [],
        'children-folders': [],
    }

    children = os.listdir(directory)
    for child in children:
        child_path = os.path.join(directory, child)
        if os.path.isdir(child_path):
            listings['children-folders'] += [get_listings( child_path )]
        else:
            listings['children-files'] += [child]


    return listings




directory = '/home/user/hello'   
print(get_listings(directory))

output is:

{
    'folder': 'hello',
    'children-files': ['a2', '1'],
    'children-folders': [{
        'folder': '002',
        'children-files': [],
        'children-folders': []
    }, {
        'folder': '001',
        'children-files': ['1'],
        'children-folders': [{
            'folder': 'aaaa',
            'children-files': ['321'],
            'children-folders': []
        }]
    }]
}

Post a Comment for "Dictionary Of Folders And Subfolders"