1

我需要制作函数,它将为给定的文件夹返回一个描述其内容的字典。Keys let 是子文件夹和文件的名称,代表文件的key值应该是它们的大小和代表文件夹的key值,是否是描述这些子文件夹内容的字典。顺序并不重要。以下是此类字典的示例:

{
   'delo' : {
      'navodila.docx' : 83273,
      'poročilo.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
}

到目前为止,我已经做到了:

import os

def izpis(map):
    slovar={}
    listFiles = os.listdir(map)
    for ts in listFiles:
        fullName = map +'\\' + ts

        if os.path.isfile(fullName):
            size=os.path.getsize(fullName)
            slovar[ts]=size
        else:
            slovar+=izpis(fullName)





    return (slovar)
4

3 回答 3

4
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
于 2013-06-10T14:04:00.720 回答
1
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
})
于 2013-06-10T16:44:35.337 回答
1
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))

输出是:

{
    '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': []
        }]
    }]
}
于 2018-12-13T03:28:05.207 回答