具體代碼:
#coding:utf-8
import os,sys,platform
class RemoveTagFile(object):
path=None
def removeFile(self,path,remove_list,retain_list): #path后面要跟/
self.path=path
system_test=platform.system()
if(system_test=='Windows'):
path_last=self.path[-1]
if(path_last!='\\' ):
self.path=self.path+'\\'
elif(system_test=='Linux'):
path_last = self.path[-1]
if (path_last != '/'):
self.path = self.path + '/'
if(len(remove_list)==0 and len(retain_list)==0): #如果remove_list,retain_list都是空則刪除path目錄下所有文件及文件夾
self.remove_file(self.eachFile(self.path))
elif(len(remove_list)>0 and len(retain_list)==0):
self.remove_file(remove_list)
elif(len(remove_list)==0 and len(retain_list)>0):
list=self.eachFile(self.path)
for f in retain_list:
if(f in list):
list.remove(f)
else:
print('There is no file in the directory!')
self.remove_file(list)
elif (len(remove_list) > 0 and len(retain_list) > 0):
for f in retain_list:
if(f in remove_list):
remove_list.remove(f)
self.remove_file(remove_list)
def remove_file(self,file_list):
for filename in file_list:
if(os.path.exists(self.path+filename)): #判斷文件是否存在
if(os.path.isdir(self.path+filename)):
self.del_file(self.path+filename)
else:
if(os.path.exists(self.path+filename)):
os.remove(self.path+filename)
else:
print(self.path+filename+' is not exist!')
for filename in file_list:
if(os.path.exists(self.path+filename)):
self.del_dir(self.path+filename)
def del_file(self,path): #遞歸刪除目錄及其子目錄下的文件
for i in os.listdir(path):
path_file = os.path.join(path, i) #取文件絕對路徑
if os.path.isfile(path_file): #判斷是否是文件
os.remove(path_file)
else:
self.del_file(path_file)
def del_dir(self,path): #刪除文件夾
for j in os.listdir(path):
path_file = os.path.join(path, j) # 取文件絕對路徑
if not os.listdir(path_file): #判斷文件如果為空
os.removedirs(path_file) #則刪除該空文件夾,如果不為空刪除會報異常
else:
self.del_dir(path_file)
def eachFile(self,filepath): #獲取目錄下所有文件的名稱
pathDir = os.listdir(filepath)
list=[]
for allDir in pathDir:
child = os.path.join('%s%s' % (filepath, allDir))
fileName=child.replace(filepath,'')
list.append(fileName)
return list
if __name__ == '__main__':
rtf=RemoveTagFile()
#以下表示只刪除D:\Test\目錄下的a文件夾、a.txt文件、b.txt文件
"""
規則:
1、如果remove_list、retain_list都為空則刪除path目錄下所有文件及文件夾
2、如果remove_list為空、retain_list不為空,則刪除不在retain_list中的所有文件及文件夾
3、如果remove_list不為空、retain_list為空,則刪除在remove_list中的所有文件及文件夾
4、如果remove_list、retain_list都不為空,則刪除不在retain_list中且在remove_list中的所有文件及文件夾
"""
path = 'D:\Test'
remove_list = ['a', 'a.txt', 'b.txt'] # 要刪除的文件名稱
retain_list = ['c.txt'] # 要保留的文件名稱
rtf.removeFile(path,remove_list,retain_list)