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程序设计有所帮助。

相关文章

在Python的Django框架中更新数据库数据的方法

先使用一些关键参数创建对象实例,如下: >>> p = Publisher(name='Apress', ... address='2855 Telegra...

python opencv 直方图反向投影的方法

python opencv 直方图反向投影的方法

本文介绍了python opencv 直方图反向投影的方法,分享给大家,具体如下: 目标: 直方图反向投影 原理: 反向投影可以用来做图像分割,寻找感兴趣区间。它会输出与输入图像...

列举Python中吸引人的一些特性

这里我不讨论 python 的一些有用的库或者框架,只从语言本身,最小支持的情况下谈论这门语言本身。语言的发展都是越来越接近Lisp,这也是Lisp这门语言伟大的原因。 下面我罗列一下我...

对Python中小整数对象池和大整数对象池的使用详解

1. 小整数对象池 整数在程序中的使用非常广泛,Python为了优化速度,使用了小整数对象池, 避免为整数频繁申请和销毁内存空间。 Python 对小整数的定义是 [-5, 256] 这...

Python3中lambda表达式与函数式编程讲解

简单来说,编程中提到的 lambda 表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数。其一般有如下几种使用方式: 1、lambda的一般形式是关...