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

yipeiwu_com5年前Python基础

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

将脚本存储为stripscripts.py
调用语法 : python stripscripts.py <directory>
使用范例 : 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 <directory>
 Example : python %s d:\myfiles
 This script is public domain. You can freely reuse it.
 The author is
    Sebastien SAUVAGE
    <sebsauvage at sebsauvage dot net>
    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'<script.*?>', re.IGNORECASE)
  html = regexp.sub('<script language="MonthyPythonsScript">',html)
  file = open(filepath, 'w+')
  file.write(html)
  file.close()
if len(sys.argv) > 1 :
  stripscripts( sys.argv[1] )
else:
  print message

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

相关文章

Python3匿名函数lambda介绍与使用示例

概述 匿名函数,顾名思义即没有名称的函数,和def定义的函数的最大区别在于匿名函数创建后返回函数本身(即匿名函数不需要return来返回值),表达式本身结果就是返回值,而def创建后则...

python 三元运算符使用解析

三元运算又称三目运算,是对简单的条件语句的简写 简单条件语句: if 条件成立: val = 1 else: val = 2 改成三元运算: val = 1 if 条件...

使用GitHub和Python实现持续部署的方法

使用GitHub和Python实现持续部署的方法

借助 GitHub 的网络钩子webhook,开发者可以创建很多有用的服务。从触发一个 Jenkins 实例上的 CI(持续集成) 任务到配置云中的机器,几乎有着无限的可能性。这篇教程将...

Django实战之用户认证(初始配置)

前两篇讲述了Django的理论,从这篇开始,我们真正进入Django实战部分,今天先从用户认证开始。 当大家平时打开一个网站时,第一步一般做什么?我猜大部分是先登录吧,所以我们就从用户认...

详解Python 4.0 预计推出的新功能

Python 3.8 发布在即,核心开发者团队让我总结一下最近讨论的 Python 4.0 预计推出的新功能,代码名为“ Ouroboros:自噬蛇”。Python 4.0 是大家翘首以...