python清除指定目录内所有文件中script的方法

本文实例讲述了python清除指定目录内所有文件中script的方法。分享给大家供大家参考。具体如下:

将脚本存储为stripscripts.py
调用语法 : python stripscripts.py
使用范例 : python stripscripts.py d:\myfiles

# hello, this is a script written in python. see http://www.pyhon.org
import os,sys,string,re
message = “””
stripscripts 1.1p – script stripper
this script will walk a directory (and its subdirectories) and disable
all scripts (javascript, vbscript…) from .html and .htm files.
(the scripts will not be deleted, but simply deactivated, so that
you can review them if you like.)
can be usefull for sites you have downloaded with httrack or similar tools.
no more nosey or buggy scripts in your local html files.
syntax : python %s
example : python %s d:\myfiles
this script is public domain. you can freely reuse it.
the author is
sebastien sauvage

http://sebsauvage.net
more quick & dirty scripts are available at http://sebsauvage.net/python/
“”” % ((sys.argv[0], )*2)
def stripscripts ( directorystart ) :
os.path.walk( directorystart, callback, ” )
def callback ( args, directory, files ) :
print ‘scanning’,directory
for filename in files:
if os.path.isfile( os.path.join(directory,filename) ) :
if string.lower(os.path.splitext(filename)[1]) in [‘.html’,’.htm’] :
stripscriptfromhtml ( os.path.join(directory,filename) )
def stripscriptfromhtml ( filepath ) :
print ‘ processing’,os.path.split(filepath)[1]
file = open(filepath, ‘rb’)
html = file.read()
file.close()
regexp = re.compile(r”, re.ignorecase)
html = regexp.sub(”,html)
file = open(filepath, ‘w+’)
file.write(html)
file.close()
if len(sys.argv) > 1 :
stripscripts( sys.argv[1] )
else:
print message

希望本文所述对大家的python程序设计有所帮助。