一. 前言

今早发现电脑的磁盘空间莫名其妙的占满了…也不知道是哪个文件占用了大量的内存空间。就随手写了个python,把磁盘空间全部遍历一遍,找到了大量占用磁盘空间的罪魁祸首。

二. 深度遍历磁盘下所有文件(递归)

因为Windows的目录结构采用的是树形结构,所以可以使用深度遍历或广度遍历来遍历所有的文件,这里采用的是递归方法来实现深度遍历:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93


import os





def get_files(path):


    global lst


    if not os.path.exists(path): # 判断路径是否存在


        return


    if not os.path.isdir(path):  # 判断路径是否为文件夹,若不是,则结束


        return





    # 获取该路径中所有文件\文件夹的名称


    file_list = os.listdir(path)


    


    # 遍历该路径下所有内容:


    for filename in file_list:


        try: 


            subpath = os.path.join(path, filename) # 拼接路径,获取每个次级目录下的文件路径


            if os.path.isfile(subpath):


                fsize = os.path.getsize(subpath)  # 获取该文件的大小


                fsize = fsize / float(1024 * 1024)  # 将单位转换为MB


                lst.append((fsize, subpath))


            else:


                get_files(subpath)  # 递归


        except:


            pass





if __name__ == '__main__':


    lst = []


    get_files('C:/')  # 查找C盘下的大文件


    lst.sort(key= lambda k:k[0], reverse=True) # 按照文件大小依次排序


    for i in range(50):


        print('文件路径: %s, 大小:%s MB' %(lst[i][1], round(lst[i][0], 2)))