以下就是垃圾清理程序代码 主要是os库大家可以多看看
1 import os 2 del_extension = { 3 ‘.tmp‘: ‘临时文件‘, 4 ‘._mp‘: ‘临时文件_mp‘, 5 ‘.log‘: ‘日志文件‘, 6 ‘.gid‘: ‘临时帮助文件‘, 7 ‘.chk‘: ‘磁盘检查文件‘, 8 ‘.old‘: ‘临时备份文件‘, 9 ‘.xlk‘: ‘Excel备份文件‘, 10 ‘.bak‘: ‘临时备份文件bak‘ 11 } 12 del_userprofile = [‘cookies‘, ‘recent‘, ‘Temporary Internet Files‘, ‘Temp‘] 13 del_windir = [‘prefetch‘, ‘temp‘] 14 SYS_DRIVE = os.environ[‘systemdrive‘] + ‘\\‘ 15 USER_PROFILE = os.environ[‘userprofile‘] 16 WIN_DIR = os.environ[‘windir‘] 17 18 def del_dir_or_file(root): 19 try: 20 if os.path.isfile(root): 21 os.remove(root) 22 print ("file",root,"removed") 23 elif os.path.isdir(root): 24 os.rmdir(root) 25 print("dir",root,"removed") 26 27 except WindowsError: 28 print("failure",root,"can‘t remove") 29 30 def formatSize(b): 31 try: 32 kb = b // 1024 33 except: 34 print("传入字节格式不对") 35 return "Error" 36 if kb > 1024: 37 M = kb // 1024 38 if M > 1024: 39 G = M // 1024 40 return "%dG" % G 41 else: 42 return "%dM" % M 43 else: 44 return "%dkb" % kb 45 46 class DiskClean(object): 47 def __init__(self): 48 self.del_info = {} 49 self.del_file_paths = [] 50 self.total_size = 0 51 for i,j in del_extension.items(): 52 self.del_info[i] = dict(name = j,count = 0 ) 53 54 def scanf(self): 55 for roots,dirs,files in os.walk(USER_PROFILE): 56 for files_item in files: 57 file_extension = os.path.splitext(files_item)[1] 58 if file_extension in self.del_info: 59 file_full_path = os.path.join(roots,files_item) 60 self.del_file_paths.append(file_full_path) 61 self.del_info[file_extension][‘count‘] += 1 62 self.total_size += os.path.getsize(file_full_path) 63 64 def show(self): 65 re = formatSize(self.total_size) 66 for i in self.del_info: 67 print(self.del_info[i]["name"],"共计",self.del_info[i]["count"],"个") 68 return re 69 70 def delete_files(self): 71 for i in self.del_file_paths: 72 print(i) 73 del_dir_or_file(i) 74 if __name__ == "__main__": 75 print("初始化清理垃圾程序") 76 cleaner = DiskClean() 77 print("开始扫描垃圾文件请耐心等待\n") 78 cleaner.scanf() 79 print("扫描成功,结果如下") 80 re = cleaner.show() 81 if_del = input("\n是否删除 y确认其他键结束:") 82 83 if if_del == "y" or if_del =="Y": 84 85 cleaner.delete_files() 86 print("\n☆★☆★☆★☆★☆★本次垃圾释放",re,"空间欢迎再次使用☆★☆★☆★☆★☆★\n")
原文:https://www.cnblogs.com/ruler-madman/p/13445863.html