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 相关文章推荐
python判断端口是否打开的实现代码
Feb 10 Python
web.py在SAE中的Session问题解决方法(使用mysql存储)
Jun 24 Python
Python编程中的异常处理教程
Aug 21 Python
Google开源的Python格式化工具YAPF的安装和使用教程
May 31 Python
python 实现A*算法的示例代码
Aug 13 Python
对python中类的继承与方法重写介绍
Jan 20 Python
Python3.5基础之NumPy模块的使用图文与实例详解
Apr 24 Python
python 实现返回一个列表中出现次数最多的元素方法
Jun 11 Python
Python登录系统界面实现详解
Jun 25 Python
解决Django no such table: django_session的问题
Apr 07 Python
详解用Python爬虫获取百度企业信用中企业基本信息
Jul 02 Python
python3访问字典里的值实例方法
Nov 18 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
php正则校验用户名介绍
2008/07/19 PHP
Zend Framework教程之请求对象的封装Zend_Controller_Request实例详解
2016/03/07 PHP
php+ajax实现带进度条的上传图片功能【附demo源码下载】
2016/09/14 PHP
file模式访问网页时iframe高度自适应解决方案
2013/01/16 Javascript
Jquery实现图片预加载与延时加载的方法
2014/12/22 Javascript
JavaScript中指定函数名称的相关方法
2015/06/04 Javascript
无刷新上传文件并返回自定义值
2015/06/11 Javascript
JavaScript驾驭网页-DOM
2016/03/24 Javascript
js仿3366小游戏选字游戏
2016/04/14 Javascript
省市联动效果的简单实现代码(推荐)
2016/06/06 Javascript
AngularJS 如何在控制台进行错误调试
2016/06/07 Javascript
AngularJs Javascript MVC 框架
2016/06/20 Javascript
JS代码实现百度地图 画圆 删除标注
2016/10/12 Javascript
javascript实现动态显示颜色块的报表效果
2017/04/10 Javascript
JS实现下拉菜单列表与登录注册弹窗效果
2017/08/10 Javascript
浅析Javascript中双等号(==)隐性转换机制
2017/10/27 Javascript
Vue前端开发规范整理(推荐)
2018/04/23 Javascript
js如何获取图片url的Blob值并预览示例代码
2019/03/07 Javascript
微信小程序Page中data数据操作和函数调用方法
2019/05/08 Javascript
react用Redux中央仓库实现一个todolist
2019/09/29 Javascript
小程序如何定位所在城市及发起周边搜索
2020/02/11 Javascript
Javascript地址引用代码实例解析
2020/02/25 Javascript
Vue如何基于vue-i18n实现多国语言兼容
2020/07/17 Javascript
Python中的模块和包概念介绍
2015/04/13 Python
python直接访问私有属性的简单方法
2016/07/25 Python
利用python模拟实现POST请求提交图片的方法
2017/07/25 Python
Python文本处理之按行处理大文件的方法
2018/04/09 Python
Centos部署django服务nginx+uwsgi的方法
2019/01/02 Python
超简单使用Python换脸实例
2019/03/27 Python
在python shell中运行python文件的实现
2019/12/21 Python
法学院方阵解说词
2014/01/29 职场文书
夫妻双方自愿离婚协议书怎么写
2014/12/01 职场文书
优秀党员个人总结
2015/02/14 职场文书
同学聚会通知书
2015/04/20 职场文书
python将图片转为矢量图的方法步骤
2021/03/30 Python
SQL Server使用导出向导功能
2022/04/08 SQL Server