利用python程序帮大家清理windows垃圾

  import os

  import json

  import shutil

  del_extension = {

  '.tmp': '临时文件',

  '._mp': '临时文件_mp',

  '.log': '日志文件',

  '.gid': '临时帮助文件',

  '.chk': '磁盘检查文件',

  '.old': '临时备份文件',

  '.xlk': 'Excel备份文件',

  '.bak': '临时备份文件bak'

  }

  del_userprofile = ['cookies', 'recent', 'Temporary Internet Files', 'Temp']

  del_windir = ['prefetch', 'temp']

  # 获取系统盘

  SYS_DRIVE = os.environ['systemdrive'] + '\'

  # 获取用户目录

  USER_PROFILE = os.environ['userprofile']

  # 获取 Windows 目录

  WIN_DIR = os.environ['windir']

  # 获取当前路径 os.getcwd() 'E:\Software\Python27'

  # 跳转至指定的文件目录 os.chdir('d://wamp')

  # 获取系统盘符 os.environ['systemdrive'] 'C:'

  # 获取用户目录 os.environ['userprofile'] 'C:\Users\Administrator'

  # 获取 Windows 目录 os.environ['windir'] 'C:\Windows'

  def del_dir_or_file(root):

  try:

  if os.path.isfile(root):

  # 删除文件

  os.remove(root)

  print 'file: ' + root + ' removed'

  elif os.path.isdir(root):

  # 删除文件夹

  shutil.rmtree(root)

  print 'directory: ' + root + ' removed'

  except WindowsError:

  print 'failure: ' + root + " can't remove"

  # 字节bytes转化kbmg

  def formatSize(bytes):

  try:

  bytes = float(bytes)

  kb = bytes / 1024

  except:

  print("传入的字节格式不对")

  return "Error"

  if kb >= 1024:

  M = kb / 1024

  if M >= 1024:

  G = M / 1024

  return "%fG" % (G)

  else:

  return "%fM" % (M)

  else:

  return "%fkb" % (kb)

  class DiskClean(object):

  def __init__(self):

  self.del_info = {}

  self.del_file_paths = []

  self.total_size = 0

  for k,v in del_extension.items():

  self.del_info[k] = dict(name = v, count = 0)

  def scan(self):

  for roots, dirs, files in os.walk(USER_PROFILE, topdown=False):

  # 生成并展开以 root 为根目录的目录树,参数 topdown 设定展开方式从底层到顶层

  for file_item in files:

  # 获取扩展名

  file_extension = os.path.splitext(file_item)[1]

  # print os.path.join(roots, file_item)

  if file_extension in self.del_info:

  # 文件完整路径

  file_full_path = os.path.join(roots, file_item)

  self.del_file_paths.append(file_full_path)

  self.del_info[file_extension]['count'] += 1

  self.total_size += os.path.getsize(file_full_path)

  def show(self):

  print json.dumps(self.del_info, indent=4, ensure_ascii=False)

  print '删除可节省:%s 空间' % formatSize(self.total_size)

  def delete_files(self):

  for i in self.del_file_paths:

  del_dir_or_file(i)

  if __name__ == '__main__':

  cleaner = DiskClean()

  cleaner.scan()

  cleaner.show()

  if_del = raw_input('是否删除y/n:')

  if if_del == 'y':

  cleaner.delete_files()