【问题标题】:Get size of files and folders of a path and store it in a python dictionary获取路径的文件和文件夹的大小并将其存储在 python 字典中
【发布时间】:2022-12-18 06:40:17
【问题描述】:

我想要的结果是让我选择的路径中所有内容的大小从文件到根文件夹,并将其存储在 python 字典中,如下所示:

{
    root:{
        folder1:{
            {file11:100,
             file12:89,
             file13:32},
             size:221
        },
        folder2:{
            subfolder21:{
                {file21:45,
                 file22:80},
                size:125
            },
            size:125
        },
        size:346,
    }
}

像这样我知道 root/folder1 中的 file11 它的大小是 100,我还有 folder1 的总大小,它是其中所有内容的总和,221

我设法得到这本字典

{
    root:{
        folder1:{
            {file11:100,
             file12:89,
             file13:32}
        },
        folder2:{
            subfolder21:{
                {file21:45,
                 file22:80}
            }
        }
    }
}

但是我很努力地计算文件的总和并将值分配给每个文件夹,我的代码是:

def get_dir_content(ls_path):
    for dir_path in os.listdir(ls_path):
        if dir_path.isFile():
            yield (dir_path.path, dir_path.size)
        elif dir_path.isDir() and ls_path != dir_path.path:
            yield from get_dir_content(dir_path.path)
            
x = list(get_dir_content("/path"))

d = {}
for i in x:
    l = ''
    for j in i[0].split('/'):
        l = l+"['"+j+"']" 
        try:
            exec('d'+l)
        except:
            exec('d'+l+'={}')
    exec('d'+l+'='+str(i[1]))

提前致谢

【问题讨论】:

    标签: python-3.x file dictionary directory


    【解决方案1】:

    尝试这个。

    def get_dir_content(ls_path, d):
        for dir_path in os.listdir(ls_path):
            if dir_path.isFile():
                d[dir_path.path] = dir_path.size
                yield (dir_path.path, dir_path.size)
            elif dir_path.isDir() and ls_path != dir_path.path:
                sub_dir = {dir_path.path: {}}
                d.update(sub_dir)
                yield from get_dir_content(dir_path.path, d[dir_path.path])
    
    def get_sum(d):
        for key, value in d.items():
            if isinstance(value, dict):
                d[key]['size'] = get_sum(value)
            else:
                d[key] = {'size': value}
        return sum(v['size'] for v in d.values())
    
    x = list(get_dir_content("/path", d))
    d['root']['size'] = get_sum(d['root'])
    
    print(d)
    

    如果我没有正确理解您的问题:此代码首先使用 get_dir_content() 函数遍历给定路径中的文件和文件夹。然后它检查该项目是文件还是目录,并将相应的路径和大小存储在字典中。

    如果项目是一个目录,则创建一个子字典并递归调用get_dir_content()函数以遍历目录中的文件和文件夹。

    然后调用get_sum()函数,通过将字典中的文件和文件夹的大小相加来计算目录的总大小。最后计算出根目录的大小,存入字典中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      相关资源
      最近更新 更多