Python_计算文件夹大小

计算文件夹大小

os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

os.path.getsize(path) 返回path的大小

os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
递归版:
 1 import os
 2 
 3 
 4 def get_size(path):
 5     ret = os.listdir(path)
 6     print(ret)
 7     total = 0
 8 
 9     for name in ret:
10         abs_path = os.path.join(path, name)
11 
12         if os.path.isdir(abs_path):
13             total += get_size(abs_path)
14         else:
15             total += os.path.get.size(abs_path)
16 
17     return total
18 
19 path = r'D:\S12\py笔记'
20 ret = get_size(path)
21 print(ret)

  递归什么时候结束?  返回值的时候结束递归.

堆栈

  栈是一种计算机存储数据的思想:先进后出

压栈思想:

 1 import os
 2 
 3 
 4 path = r'D:\S12\py笔记\day19'
 5 dir_lst = [path]
 6 
 7 while dir_list:
 8     path = dir_lst.pop()
 9     ret = os.listdir(path)
10 
11     for name in ret:
12         abs_path = os.path.join(path, name)
13     
14         if os.path.isdir(abs_path):
15             dir_lst.append(abs_path)
16         else:
17             total += os.path.getsize(abs_path)
18 
19 print(total)

猜你喜欢

转载自www.cnblogs.com/ZN-225/p/9614233.html