python清除指定目录内所有文件中script的方法
本文实例讲述了python清除指定目录内所有文件中script的方法。分享给大家供大家参考。具体如下:
将脚本存储为stripscripts.py
调用语法:pythonstripscripts.py<directory>
使用范例:pythonstripscripts.pyd:\myfiles
#Hello,thisisascriptwritteninPython.Seehttp://www.pyhon.org
importos,sys,string,re
message="""
stripscripts1.1p-Scriptstripper
Thisscriptwillwalkadirectory(anditssubdirectories)anddisable
allscripts(javascript,vbscript...)from.htmland.htmfiles.
(Thescriptswillnotbedeleted,butsimplydeactivated,sothat
youcanreviewthemifyoulike.)
CanbeusefullforsitesyouhavedownloadedwithHTTrackorsimilartools.
Nomorenoseyorbuggyscriptsinyourlocalhtmlfiles.
Syntax:python%s<directory>
Example:python%sd:\myfiles
Thisscriptispublicdomain.Youcanfreelyreuseit.
Theauthoris
SebastienSAUVAGE
<sebsauvageatsebsauvagedotnet>
http://sebsauvage.net
Morequick&dirtyscriptsareavailableathttp://sebsauvage.net/python/
"""%((sys.argv[0],)*2)
defstripscripts(directoryStart):
os.path.walk(directoryStart,callback,'')
defcallback(args,directory,files):
print'Scanning',directory
forfileNameinfiles:
ifos.path.isfile(os.path.join(directory,fileName)):
ifstring.lower(os.path.splitext(fileName)[1])in['.html','.htm']:
stripScriptFromHtml(os.path.join(directory,fileName))
defstripScriptFromHtml(filepath):
print'Processing',os.path.split(filepath)[1]
file=open(filepath,'rb')
html=file.read()
file.close()
regexp=re.compile(r'<script.*?>',re.IGNORECASE)
html=regexp.sub('<scriptlanguage="MonthyPythonsScript">',html)
file=open(filepath,'w+')
file.write(html)
file.close()
iflen(sys.argv)>1:
stripscripts(sys.argv[1])
else:
printmessage
希望本文所述对大家的Python程序设计有所帮助。