核心功能 - 清理下载文件夹

世界上最混乱的事情之一是开发人员的下载文件夹,里面存放了很多杂乱无章的文件,此脚本将根据大小限制来清理您的下载文件夹,有限清理比较旧的文件。

实现代码

  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
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165


import os 


import threading 


import time 


   


   


def get_file_list(file_path): 


#文件按最后修改时间排序 


    dir_list = os.listdir(file_path) 


    if not dir_list: 


        return


    else: 


        dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x))) 


    return dir_list 


   


def get_size(file_path): 


    """[summary] 


    Args: 


        file_path ([type]): [目录] 


  


    Returns: 


        [type]: 返回目录大小,MB 


    """


    totalsize=0


    for filename in os.listdir(file_path): 


        totalsize=totalsize+os.path.getsize(os.path.join(file_path, filename)) 


    #print(totalsize / 1024 / 1024) 


    return totalsize / 1024 / 1024


   


def detect_file_size(file_path, size_Max, size_Del): 


    """[summary] 


    Args: 


        file_path ([type]): [文件目录] 


        size_Max ([type]): [文件夹最大大小] 


        size_Del ([type]): [超过size_Max时要删除的大小] 


    """


    print(get_size(file_path)) 


    if get_size(file_path) > size_Max: 


        fileList = get_file_list(file_path) 


        for i in range(len(fileList)): 


            if get_size(file_path) > (size_Max - size_Del): 


                print ("del :%d %s" % (i + 1, fileList[i])) 


                #os.remove(file_path + fileList[i]) 


      


   


def detectFileSize(): 


 #检测线程,每个5秒检测一次 


    while True: 


        print('======detect============') 


        detect_file_size("/Users/aaron/Downloads/", 100, 30) 


        time.sleep(5) 


    


if __name__ == "__main__": 


    #创建检测线程 


    detect_thread = threading.Thread(target = detectFileSize) 


    detect_thread.start()