一,递归写
import os def func(filepath): size_sum = 0 files = os.listdir(filepath) for file in files: f_d = os.path.join(filepath,file) if os.path.isdir(f_d): size = func(f_d) size_sum += size else: size_sum += os.path.getsize(filepath) return size_sum print(func(r'C:\Users\LIANG\Desktop\pythonS15\python学习s15'))
二,循环写
lst = [r'D:\sylar\s15'] size_sum = 0 while lst: path = lst.pop() path_list = os.listdir(path) for name in path_list: abs_path = os.path.join(path,name) if os.path.isdir(abs_path): lst.append(abs_path) else: size_sum += os.path.getsize(abs_path) print(size_sum)