文件夹和子文件夹的字典 [英] dictionary of folders and subfolders

查看:188
本文介绍了文件夹和子文件夹的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做一个函数,它将返回一个给定的文件夹,一个描述其内容的Dictionary。键可以是子文件夹和文件的名称,表示文件的键值应该是它们的大小和代表文件夹的键值,无论它们是描述这些子文件夹的内容的字典。这个顺序并不重要。这是一个这样的字典的例子:

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 the file should be their size and key values ​​that represent folders, whether they are dictionaries that describe the content of these subfolders. The order is not important. Here is an example of such a dictionary:

{
   '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)


推荐答案

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

这篇关于文件夹和子文件夹的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆