Python:递归计算文件夹和子文件夹中的所有文件类型和大小

问题描述 投票:0回答:1

我正在尝试按类型和所有大小来统计目录中的所有文件和任何子目录

输出应该是一个看起来像这样的表:

Directory A             
Number of subdirectories: 12    

|Type|  Count|  TotalSize/kb    |FirstSeen  |LastSeen  |
|----|-------|------------------|-----------|----------|
|.pdf|  8    |80767             |1/1/2020   |2/20/2020 | 
|.ppt|  9    |2345              |1/5/2020   |2/25/2020 |
|.mov|  2    |234563            |1/10/2020  |3/1/2020  | 
|.jpg|  14   |117639            |1/15/2020  |3/5/2020  |
|.doc|  5    |891               |1/20/2020  |3/10/2020 |

抱歉,我正试图将其转换为表格格式以提高可读性。但是每条记录都以在目录中找到的文件类型开头。

python directory subdirectory
1个回答
-1
投票

这应该完全满足您的要求,计算扩展名映射的大小。整理一下,按照自己喜欢的方式打印,就可以完成。

import os

def scan_dir(root_dir):
    # walk the directory
    result = {}
    for root, dirs, files in os.walk(root_dir):
        # count the files size
        for file in files:
            path = os.path.join(root, file)
            ext = os.path.splitext(file)[1].upper()
            size = os.stat(path).st_size
            result[ext] = (result[ext] if ext in result else 0) + size
    return result

print(scan_dir("."))

编辑:这不会为您收集最小/最大时间戳,也不会计算文件,但这确实可以使您走上正确的轨道。

© www.soinside.com 2019 - 2024. All rights reserved.