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 pandas读取csv后,获取列标签的方法

在Python中,经常会去读csv文件,如下 import pandas as pd import numpy as np df = pd.read_csv("path.csv")...

python进阶之自定义可迭代的类

自定义可迭代的类 列表可以获取列表的长度,然后使用变量i对列表索引进行循环,也可以获取集合的所有元素,且容易理解。没错,使用列表的代码是容易理解,也很好操作,但这是要付出代价的。列表之所...

Python利用多进程将大量数据放入有限内存的教程

Python利用多进程将大量数据放入有限内存的教程

简介 这是一篇有关如何将大量的数据放入有限的内存中的简略教程。 与客户工作时,有时会发现他们的数据库实际上只是一个csv或Excel文件仓库,你只能将就着用,经常需要在不更新他们的数据仓...

python基础教程之缩进介绍

Python的运算符和其他语言类似 (我们暂时只了解这些运算符的基本用法,方便我们展开后面的内容,高级应用暂时不介绍) 数学运算 复制代码 代码如下: >>>print...

Python字典生成式、集合生成式、生成器用法实例分析

本文实例讲述了Python字典生成式、集合生成式、生成器用法。分享给大家供大家参考,具体如下: 字典生成式: 跟列表生成式一样,字典生成式用来快速生成字典,不同的是,字典需要两个值...