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结巴中文分词工具使用过程中遇到的问题及解决方法

Python结巴中文分词工具使用过程中遇到的问题及解决方法

本文实例讲述了Python结巴中文分词工具使用过程中遇到的问题及解决方法。分享给大家供大家参考,具体如下: 结巴分词是Python语言中效果最好的分词工具,其功能包括:分词、词性标注、关...

Python使用统计函数绘制简单图形实例代码

Python使用统计函数绘制简单图形实例代码

前言 Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。 它也可以和图形工具包一起使用,如 PyQt 和 w...

linux平台使用Python制作BT种子并获取BT种子信息的方法

本文实例讲述了linux平台使用Python制作BT种子并获取BT种子信息的方法。分享给大家供大家参考,具体如下: 最近研究了一下linux BT服务器环境的搭建,需要在linux下制作...

学习python类方法与对象方法

学习python类方法与对象方法

本文实例针对python的类方法与对象方法进行学习研究,具体内容如下 class Test_Demo: TEST = 'test_value' def __init__(s...

关于Python内存分配时的小秘密分享

关于Python内存分配时的小秘密分享

前言 Python 中的sys 模块极为基础而重要,它主要提供了一些给解释器使用(或由它维护)的变量,以及一些与解释器强交互的函数。 本文将会频繁地使用该模块的getsizeof()...