Python删除windows垃圾文件的方法

yipeiwu_com6年前Python基础

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

#coding:utf-8
import os
#from glob import glob
if os.name == 'nt':
 if 'HOMEPATH' in os.environ:
 home = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
 else:
 home = os.environ['HOMEPATH']
workpath = os.path.join(home,'Local Settings')
#递归删除文件
#里面和下面的函数用try是抛出删除正在使用的零时文件出错
def delfile(path):
 for file in os.listdir(path): 
 if os.path.isfile(os.path.join(path,file)):
  try:
  print "\n删除垃圾文件: %s" % (os.path.join(path,file))
  os.remove(os.path.join(path,file))
  except:
  pass
 elif os.path.isdir(os.path.join(path,file)):
  delfile(os.path.join(path,file)) 
 else:
  pass
delfile(os.path.join(workpath,'Temp'))
delfile(os.path.join(workpath,'Temporary Internet Files'))
#删除文件家的时候必须为空文件夹,而且只能从最里层删起
def deldir(pa):
 for i in os.listdir(pa):
 if os.path.isdir(os.path.join(pa,i)):
  if len(os.listdir(os.path.join(pa,i))) > 0:
  deldir(os.path.join(pa,i))
  try:
   os.rmdir(os.path.join(pa,i))
  except:
   pass
  else:
  try:
   print "\n删除文件夹 %s" % (os.path.join(pa,i))
   os.rmdir(os.path.join(pa,i))
  except:
   pass
deldir(os.path.join(workpath,'Temp'))
deldir(os.path.join(workpath,'Temporary Internet Files'))
print """
 系统产生的零时垃圾文件清理完毕!
 """
raw_input("请按回车键退出!")

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

相关文章

pandas 数据索引与选取的实现方法

我们对 DataFrame 进行选择,大抵从这三个层次考虑:行列、区域、单元格。 其对应使用的方法如下: 一. 行,列 --> df[] 二. 区域   --...

解析Python的缩进规则的使用

Python中的缩进(Indentation)决定了代码的作用域范围。这一点和传统的c/c++有很大的不同(传统的c/c++使用花括号{}符,python使用缩进空格)。 每行代码中开头...

python gdal安装与简单使用

python gdal安装与简单使用

gdal安装 方式一:在网址 https://www.lfd.uci.edu/~gohlke/pythonlibs/ 下载对应python版本的whl文件,在命令行中pip instal...

学习python (1)

先推荐一个学习python的好网址简明 Python 教程 Swaroop, C. H. 著 沈洁元  译在线教程的网址:http://www.woodpecker.org.cn:...

Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能示例

Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能示例

本文实例讲述了Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能。分享给大家供大家参考,具体如下: 【吐槽】 网上的代码害死人,看着都写的言之凿凿,可运行就是...