100 lines
2.8 KiB
Python
100 lines
2.8 KiB
Python
|
# 工具功能:
|
||
|
# 遍历指定文件夹,留下需要的文件(使用后缀名识别),并且删除空文件夹
|
||
|
# 随后删除指定文件夹。(可选)
|
||
|
# 然后把这个文件夹压缩
|
||
|
import os
|
||
|
import shutil
|
||
|
import zipfile
|
||
|
|
||
|
|
||
|
class de_non_executable(object):
|
||
|
|
||
|
def __init__(self):
|
||
|
pass
|
||
|
|
||
|
def fileFilter(self,dirpath):
|
||
|
"""
|
||
|
|
||
|
:param dirpath:
|
||
|
:return:
|
||
|
"""
|
||
|
for root, dirs, files in os.walk(dirpath):
|
||
|
for file in files:
|
||
|
# 获取文件所属目录
|
||
|
# 获取文件路径
|
||
|
rFindFileIndex = file.rfind('.')
|
||
|
fileExtname = file[rFindFileIndex + 1:]
|
||
|
# 删除指定后缀名的文件
|
||
|
targetMalwarepath = os.path.join(root, file)
|
||
|
print(targetMalwarepath)
|
||
|
if (fileExtname == 'pdf' or fileExtname == 'txt' or fileExtname == 'dll'):
|
||
|
os.remove(os.path.join(root, file))
|
||
|
print('删除不需要的文件' + file)
|
||
|
else:
|
||
|
pass
|
||
|
# 删除空文件夹
|
||
|
if not os.listdir(root):
|
||
|
print("文件夹" + root + "为空,删除")
|
||
|
os.rmdir(root)
|
||
|
# 删除指定名称的文件夹
|
||
|
for roots in root:
|
||
|
if roots == '新建文件夹':
|
||
|
shutil.rmtree(roots)
|
||
|
os.mkdir(roots)
|
||
|
print("已留下所需文件")
|
||
|
|
||
|
|
||
|
|
||
|
# 删除空文件夹
|
||
|
def delete_null_dirs(self,dires):
|
||
|
dirs_list = []
|
||
|
for root, dirs, files in os.walk(dires):
|
||
|
dirs_list.append(root)
|
||
|
for root in dirs_list[::-1]:
|
||
|
if not os.listdir(root):
|
||
|
print("删除空目录:" + root)
|
||
|
os.rmdir(root)
|
||
|
|
||
|
|
||
|
|
||
|
# 压缩文件夹
|
||
|
def zipdir(self,srcPath, dstname):
|
||
|
workzip = zipfile.ZipFile(dstname, "w", zipfile.ZIP_DEFLATED)
|
||
|
for dirpath, dirs, files in os.walk(srcPath):
|
||
|
for filename in files:
|
||
|
workzip.write(os.path.join(dirpath, filename))
|
||
|
print(filename + "压缩完成")
|
||
|
workzip.close
|
||
|
|
||
|
|
||
|
|
||
|
# 获取操作文件夹名称
|
||
|
def direname(self,dirspath):
|
||
|
finddirIndex = dirpath.split("\\")
|
||
|
global dirname
|
||
|
dirname = finddirIndex[-1]
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
dirpath = str("./test")
|
||
|
dirname = ''
|
||
|
|
||
|
# fileFilter(dirpath)
|
||
|
# delete_null_dirs(dirpath)
|
||
|
# direname(dirpath)
|
||
|
# zipdir(dirpath, dirname + ".zip")
|
||
|
# print("完成,按任意键退出")
|
||
|
# input()
|
||
|
|
||
|
denoexe=de_non_executable()
|
||
|
denoexe.fileFilter(dirpath="./test")
|
||
|
denoexe.delete_null_dirs(dires="./test")
|
||
|
denoexe.direname(dirspath="./test")
|
||
|
denoexe.zipdir(srcPath="./test",dstname=''+".zip")
|
||
|
print("完成,按任意键退出")
|
||
|
input()
|
||
|
|
||
|
|