python 统计一个文件,或目录的大小 需要用到递归方法

import os


# 目录大小统计
def size(file):
    # 判断是否存在
    if not os.path.exists(file):
        print(file, '文件不存在,无法统计')
        return None
    # 是普通文件
    if os.path.isfile(file):
        return os.path.getsize(file)
    # 是目录,递归统计里面的文件,最终得出目录的大小
    total = 0
    dirs = os.listdir(file)
    for f in dirs:
        file_name = os.path.join(file, f)
        if os.path.isfile(file_name):
            total += os.path.getsize(file_name)
        else:
            total += size(file_name)
    return total


print(size('test'))

 思路:

①先判断文件存不存在

②在的话,看看是不是普通文件

③是普通文件的话,直接用os.path.getsize()得到文件的大小

④是目录的话用递归统计里面各个文件的大小,最终得到总目录的大小

注意:注意各个文件的路径,路径错了会提示文件不存在无法统计

猜你喜欢

转载自blog.csdn.net/qq_42467563/article/details/82958662
今日推荐