使用python写一个Windows删除垃圾文件的脚本

暴力点,直接上代码!
脚本调用方法:cmd命令行下执行python delfile.py 目标目录 用正则表达式表述的拟删除的文件名,可携带多个参数,以空格分隔。
例如删除指定目录下所有的log,txt,xls,zip,bmp文件,python delfile.py c:\Users\Administrator *.log *.txt *.xls *.zip *.bmp

delfile.py
#!/usr/bin/python

* coding: gbk *

import sys
import platform
import shutil
import re
import os

def delete_file(fpath, kw1):
# print “清理", fpath, " 目录
try:
dirls = os.listdir(fpath)
except WindowsError:
print “Windows error, List dir”, fpath, " failed !"
return
# print “+++++”, fpath, kw1, “++++++”
for d1 in dirls:
for k1 in kw1:
p1 = fpath + “\” + d1
if os.path.isdir(p1):
if re.findall(repr(k1), repr(d1)):
print "delete directory ", p1
try:
shutil.rmtree(p1)
except WindowsError:
print "Delete directory “, p1, " failed!”
else:
delete_file(p1, kw1)
else:
pattern1 = k1
if re.compile(repr(pattern1)).findall(repr(d1)):
print "delete file ", p1
try:
os.remove(p1)
except WindowsError:
print "Windows error! Delete file “, p1, " failed!”
else:
continue

if len(sys.argv) > 1:
d_path = sys.argv[1]
else:
d_path = “”
key_word = []
if len(d_path) == 0:
print “您没有输入任何参数,程序退出!”
exit(0)

for i in range(2, len(sys.argv)):
key_word.append(sys.argv[i])

print type(key_word[0])

if platform.system() == “Windows”:
print “当前的OS是:”, platform.system()
if len(key_word) == 0:
ask1 = raw_input(“Do you really want to delete the hole directory?: y/n\t”)
if ask1 == ‘y’:
shutil.rmtree(d_path)
else:
print “You didn’t input ‘y’,so script exit!”
else:
delete_file(d_path, key_word)

if platform.system() == “Linux”:
print “当前的OS是:”, platform.system()
if len(key_word) == 0:
ask1 = raw_input(“Do you really want to delete the hole directory? y/n”)
if ask1 == ‘y’:
shutil.rmtree(d_path)
else:
print “You didn’t input y,so script exit!”
else:
pass

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值