首页 > 编程 > Python > 正文

Python删除windows垃圾文件的方法

2020-01-04 18:04:47
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了Python删除windows垃圾文件的方法,涉及Python针对系统垃圾文件的查找与清理技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了Python删除windows垃圾文件的方法。分享给大家供大家参考。具体如下:

 

 
  1. #coding:utf-8 
  2. import os 
  3. #from glob import glob 
  4. if os.name == 'nt': 
  5. if 'HOMEPATH' in os.environ: 
  6. home = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH'] 
  7. else: 
  8. home = os.environ['HOMEPATH'] 
  9. workpath = os.path.join(home,'Local Settings') 
  10. #递归删除文件 
  11. #里面和下面的函数用try是抛出删除正在使用的零时文件出错 
  12. def delfile(path): 
  13. for file in os.listdir(path):  
  14. if os.path.isfile(os.path.join(path,file)): 
  15. try: 
  16. print "/n删除垃圾文件: %s" % (os.path.join(path,file)) 
  17. os.remove(os.path.join(path,file)) 
  18. except: 
  19. pass 
  20. elif os.path.isdir(os.path.join(path,file)): 
  21. delfile(os.path.join(path,file))  
  22. else: 
  23. pass 
  24. delfile(os.path.join(workpath,'Temp')) 
  25. delfile(os.path.join(workpath,'Temporary Internet Files')) 
  26. #删除文件家的时候必须为空文件夹,而且只能从最里层删起 
  27. def deldir(pa): 
  28. for i in os.listdir(pa): 
  29. if os.path.isdir(os.path.join(pa,i)): 
  30. if len(os.listdir(os.path.join(pa,i))) > 0: 
  31. deldir(os.path.join(pa,i)) 
  32. try: 
  33. os.rmdir(os.path.join(pa,i)) 
  34. except: 
  35. pass 
  36. else: 
  37. try: 
  38. print "/n删除文件夹 %s" % (os.path.join(pa,i)) 
  39. os.rmdir(os.path.join(pa,i)) 
  40. except: 
  41. pass 
  42. deldir(os.path.join(workpath,'Temp')) 
  43. deldir(os.path.join(workpath,'Temporary Internet Files')) 
  44. print """ 
  45. 系统产生的零时垃圾文件清理完毕! 
  46. """ 
  47. raw_input("请按回车键退出!") 

希望本文所述对大家的Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表