计算文件夹大小
1.使用walk方法
def func(): import os path = r'E:\PYTHON\OldboyClass\code\学习过程代码\day24\文件' result = 0 file = os.walk(path) print(file) for a,b,c in file: print(a,b,c) for item in c: memory = os.stat(os.path.join(a,item)).st_size result+=memory return result m = func() print(m)
2.使用lisdir方法
import os PATH = r'E:\PYTHON\OldboyClass\code\学习过程代码\day24\文件' def func(): total_size = 0 lis = [PATH] while True: flag = True new_lis = [] for item in lis: item1 = os.listdir(item) for each_item1 in item1: new_path = os.path.join(item, each_item1) if os.path.isfile(new_path): file_size1 = os.path.getsize(new_path) total_size+=file_size1 else: path = os.path.join(item, new_path) new_lis.append(path) flag = False lis = new_lis if flag: return total_size result = func() print(result)
3.lisdir计算文件夹大小(进阶)
import os path = r'E:\PYTHON\OldboyClass\code\学习过程代码\day24\文件' lis = [path] total_size = 0 while lis: path = lis.pop(0) """ 把每一层的路径全部都加到列表中 , 每删除一个求一个文件的大小 , 类似于列表或栈的思想 """ for item in os.listdir(path): abs_path = os.path.join(path,item) if os.path.isfile(abs_path): size = os.path.getsize(abs_path) total_size += size else: lis.append(abs_path) print(total_size)