本文實例講述了Python刪除windows垃圾文件的方法。分享給大家供大家參考。具體如下:
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
|
#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程序設計有所幫助。