#coding=utf-8
import os,sys,re
class DeleteFile:
# 若文件名中含有. 则在其前面添加转义字符\
def addEsc(self,str):
if str.__contains__('.'):
strs = str.split('.')
transStr = strs[0]
for s in strs[1]:
transStr = transStr + '\.' + s
return transStr
else:
return str
# 根据文件名类型返回不同的正则表达式
def getRegular(self,fileName):
# 给文件名添加转义字符
fileName = self.addEsc(fileName)
if not fileName.__contains__('*'):
return fileName
elif fileName.startswith('*')&fileName.endswith('*'):
words = fileName.split('*')
ruleName = '.*' + words[1] + '.*'
return ruleName
elif fileName.startswith('*'):
words = fileName.split('*')
ruleName = '.*' + words[1]
return ruleName
elif fileName.endswith('*'):
words = fileName.split('*')
ruleName = words[0] + '.*'
return ruleName
else:
words = fileName.split('*')
ruleName = words[0] + '.*' + words[1]
return ruleName
# 删除单个目录下符合某种规则的文件 dirName -- 指定目录 , fileName -- 文件名规则
def deleteFile(self,dirName,fileName):
ruleName = self.getRegular(fileName)
try:
if os.path.exists(dirName):
ls = os.listdir(dirName)
else:
print "location doesn't exit !"
return
except:
print "error"
return
else:
for fn in ls:
temp = os.path.join(dirName,fn)
# 对目录下子文件夹不做任何操作
if(os.path.isdir(temp)):
pass
else:
# 匹配正则表达式
if re.match(ruleName,fn):
os.remove(temp)
print "delete "+temp
else:
pass
# 根据参数来删除多个目录下的符合多个规则文件
def deleteFilesByParam(self,dirs,files):
for dir in dirs:
for fileName in files:
ruleName = self.getRegular(fileName)
self.deleteFile(dir.strip(),ruleName)
python 删除指定目录下的指定名字的文件
最新推荐文章于 2024-02-03 05:30:00 发布