python实现的用于搜索文件并进行内容替换的类实例


Posted in Python onJune 28, 2015

本文实例讲述了python实现的用于搜索文件并进行内容替换的类。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/python -O
# coding: UTF-8
"""
-replace string in files (recursive)
-display the difference.
v0.2
 - search_string can be a re.compile() object -> use re.sub for replacing
v0.1
 - initial version
  Useable by a small "client" script, e.g.:
-------------------------------------------------------------------------------
#!/usr/bin/python -O
# coding: UTF-8
import sys, re
#sys.path.insert(0,"/path/to/git/repro/") # Please change path
from replace_in_files import SearchAndReplace
SearchAndReplace(
  search_path = "/to/the/files/",
  # e.g.: simple string replace:
  search_string = 'the old string',
  replace_string = 'the new string',
  # e.g.: Regular expression replacing (used re.sub)
  #search_string = re.compile('{% url (.*?) %}'),
  #replace_string = "{% url '\g<1>' %}",
  search_only = True, # Display only the difference
  #search_only = False, # write the new content
  file_filter=("*.py",), # fnmatch-Filter
)
-------------------------------------------------------------------------------
:copyleft: 2009-2011 by Jens Diemer
"""
__author__ = "Jens Diemer"
__license__ = """GNU General Public License v3 or above -
 http://www.opensource.org/licenses/gpl-license.php"""
__url__ = "http://www.jensdiemer.de"
__version__ = "0.2"
import os, re, time, fnmatch, difflib
# FIXME: see http://stackoverflow.com/questions/4730121/cant-get-an-objects-class-name-in-python
RE_TYPE = type(re.compile(""))
class SearchAndReplace(object):
  def __init__(self, search_path, search_string, replace_string,
                    search_only=True, file_filter=("*.*",)):
    self.search_path = search_path
    self.search_string = search_string
    self.replace_string = replace_string
    self.search_only = search_only
    self.file_filter = file_filter
    assert isinstance(self.file_filter, (list, tuple))
    # FIXME: see http://stackoverflow.com/questions/4730121/cant-get-an-objects-class-name-in-python
    self.is_re = isinstance(self.search_string, RE_TYPE)
    print "Search '%s' in [%s]..." % (
      self.search_string, self.search_path
    )
    print "_" * 80
    time_begin = time.time()
    file_count = self.walk()
    print "_" * 80
    print "%s files searched in %0.2fsec." % (
      file_count, (time.time() - time_begin)
    )
  def walk(self):
    file_count = 0
    for root, dirlist, filelist in os.walk(self.search_path):
      if ".svn" in root:
        continue
      for filename in filelist:
        for file_filter in self.file_filter:
          if fnmatch.fnmatch(filename, file_filter):
            self.search_file(os.path.join(root, filename))
            file_count += 1
    return file_count
  def search_file(self, filepath):
    f = file(filepath, "r")
    old_content = f.read()
    f.close()
    if self.is_re or self.search_string in old_content:
      new_content = self.replace_content(old_content, filepath)
      if self.is_re and new_content == old_content:
        return
      print filepath
      self.display_plaintext_diff(old_content, new_content)
  def replace_content(self, old_content, filepath):
    if self.is_re:
      new_content = self.search_string.sub(self.replace_string, old_content)
      if new_content == old_content:
        return old_content
    else:
      new_content = old_content.replace(
        self.search_string, self.replace_string
      )
    if self.search_only != False:
      return new_content
    print "Write new content into %s..." % filepath,
    try:
      f = file(filepath, "w")
      f.write(new_content)
      f.close()
    except IOError, msg:
      print "Error:", msg
    else:
      print "OK"
    print
    return new_content
  def display_plaintext_diff(self, content1, content2):
    """
    Display a diff.
    """
    content1 = content1.splitlines()
    content2 = content2.splitlines()
    diff = difflib.Differ().compare(content1, content2)
    def is_diff_line(line):
      for char in ("-", "+", "?"):
        if line.startswith(char):
          return True
      return False
    print "line | text\n-------------------------------------------"
    old_line = ""
    in_block = False
    old_lineno = lineno = 0
    for line in diff:
      if line.startswith(" ") or line.startswith("+"):
        lineno += 1
      if old_lineno == lineno:
        display_line = "%4s | %s" % ("", line.rstrip())
      else:
        display_line = "%4s | %s" % (lineno, line.rstrip())
      if is_diff_line(line):
        if not in_block:
          print "..."
          # Display previous line
          print old_line
          in_block = True
        print display_line
      else:
        if in_block:
          # Display the next line aber a diff-block
          print display_line
        in_block = False
      old_line = display_line
      old_lineno = lineno
    print "..."
if __name__ == "__main__":
  SearchAndReplace(
    search_path=".",
    # e.g.: simple string replace:
    search_string='the old string',
    replace_string='the new string',
    # e.g.: Regular expression replacing (used re.sub)
    #search_string  = re.compile('{% url (.*?) %}'),
    #replace_string = "{% url '\g<1>' %}",
    search_only=True, # Display only the difference
#    search_only   = False, # write the new content
    file_filter=("*.py",), # fnmatch-Filter
  )

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

Python 相关文章推荐
使用wxpython实现的一个简单图片浏览器实例
Jul 10 Python
Python实现的检测web服务器健康状况的小程序
Sep 17 Python
python使用wmi模块获取windows下硬盘信息的方法
May 15 Python
浅谈python抛出异常、自定义异常, 传递异常
Jun 20 Python
python如何去除字符串中不想要的字符
Jul 05 Python
Python异常处理操作实例详解
May 10 Python
在python中bool函数的取值方法
Nov 01 Python
Python 从相对路径下import的方法
Dec 04 Python
pytorch实现onehot编码转为普通label标签
Jan 02 Python
PyInstaller将Python文件打包为exe后如何反编译(破解源码)以及防止反编译
Apr 15 Python
python与c语言的语法有哪些不一样的
Sep 13 Python
Python利用socket模块开发简单的端口扫描工具的实现
Jan 27 Python
python实现简单ftp客户端的方法
Jun 28 #Python
基于进程内通讯的python聊天室实现方法
Jun 28 #Python
python实现的简单RPG游戏流程实例
Jun 28 #Python
python实现自动登录人人网并采集信息的方法
Jun 28 #Python
Python实现将绝对URL替换成相对URL的方法
Jun 28 #Python
python实现将html表格转换成CSV文件的方法
Jun 28 #Python
python实现根据主机名字获得所有ip地址的方法
Jun 28 #Python
You might like
第十三节--对象串行化
2006/11/16 PHP
PHP实现利用MySQL保存session的方法
2014/08/23 PHP
php实现根据词频生成tag云的方法
2015/04/17 PHP
php强制用户转向www域名的方法
2015/06/19 PHP
详细解读PHP的Yii框架中登陆功能的实现
2015/08/21 PHP
jQuery prev ~ siblings选择器使用介绍
2013/08/09 Javascript
写JQuery插件的基本知识
2013/11/25 Javascript
jQuery产品间断向下滚动效果核心代码
2014/05/08 Javascript
Jquery插件实现点击获取验证码后60秒内禁止重新获取
2015/03/13 Javascript
AngularJS学习笔记之基本指令(init、repeat)
2015/06/16 Javascript
使用JavaScript实现旋转的彩圈特效
2015/06/23 Javascript
jquery实现的简单二级菜单效果代码
2015/09/22 Javascript
JS查找字符串中出现次数最多的字符
2016/09/05 Javascript
如何处理JSON中的特殊字符
2016/11/30 Javascript
基于Koa2写个脚手架模拟接口服务的方法
2018/11/27 Javascript
如何在node环境实现“get数据解析”代码实例
2020/07/03 Javascript
原生js实现点击按钮复制内容到剪切板
2020/11/19 Javascript
好用的Python编辑器WingIDE的使用经验总结
2016/08/31 Python
Python实现遍历目录的方法【测试可用】
2017/03/22 Python
详解Python list 与 NumPy.ndarry 切片之间的对比
2017/07/24 Python
详解tensorflow实现迁移学习实例
2018/02/10 Python
Python之修改图片像素值的方法
2019/07/03 Python
python中使用while循环的实例
2019/08/05 Python
pyspark给dataframe增加新的一列的实现示例
2020/04/24 Python
Django多层嵌套ManyToMany字段ORM操作详解
2020/05/19 Python
JupyterNotebook 输出窗口的显示效果调整实现
2020/09/22 Python
印尼值得信赖的在线交易网站:Bukalapak
2019/03/11 全球购物
房产销售经理职责
2013/12/20 职场文书
网吧最新创业计划书范文
2014/03/27 职场文书
预备党员综合考察材料
2014/05/31 职场文书
党政领导班子四风问题对照检查材料思想汇报
2014/10/02 职场文书
观看《杨善洲》宣传教育片心得体会
2016/01/23 职场文书
什么是执行力?9个故事告诉您:成功绝非偶然!
2019/07/05 职场文书
一道JS算法面试题——冒泡、选择排序
2021/04/21 Javascript
在python中实现导入一个需要传参的模块
2021/05/12 Python
Lombok的详细使用及优缺点总结
2021/07/15 Java/Android