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爬虫入门教程之糗百图片爬虫代码分享
Sep 02 Python
python多线程方式执行多个bat代码
Jun 07 Python
Python单元测试简单示例
Jul 03 Python
python语言元素知识点详解
May 15 Python
python的debug实用工具 pdb详解
Jul 12 Python
python Web flask 视图内容和模板实现代码
Aug 23 Python
基于Python爬取爱奇艺资源过程解析
Mar 02 Python
python读取当前目录下的CSV文件数据
Mar 11 Python
Python3爬虫关于识别点触点选验证码的实例讲解
Jul 30 Python
Anaconda使用IDLE的实现示例
Sep 23 Python
python 图像增强算法实现详解
Jan 24 Python
Django + Taro 前后端分离项目实现企业微信登录功能
Apr 07 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实现天干地支计算器示例
2014/03/14 PHP
PHP生成短网址的3种方法代码实例
2014/07/08 PHP
取得单条网站评论以数组形式进行输出
2014/07/28 PHP
PHP模板引擎Smarty内建函数详解
2016/04/11 PHP
使用php从身份证号中获取一系列线索(星座、生肖、生日等)
2016/05/11 PHP
php封装json通信接口详解及实例
2017/03/07 PHP
yii2项目实战之restful api授权验证详解
2017/05/20 PHP
php 调用百度sms来发送短信的实现示例
2018/11/02 PHP
PHP程序员简单的开展服务治理架构操作详解(三)
2020/05/14 PHP
jQuery 可以拖动的div实现代码 脚本之家修正版
2009/06/26 Javascript
document.getElementById方法在Firefox与IE中的区别
2010/05/18 Javascript
JQuery AJAX提交中文乱码的解决方案
2010/07/02 Javascript
javascript的函数、创建对象、封装、属性和方法、继承
2011/03/10 Javascript
模拟select的代码
2011/10/19 Javascript
js的表单操作 简单计算器
2011/12/29 Javascript
js页面跳转的问题(跳转到父页面、最外层页面、本页面)
2013/08/14 Javascript
NodeJS Express框架中处理404页面一个方式
2014/05/28 NodeJs
js自定义鼠标右键的实现原理及源码
2014/06/23 Javascript
jquery实现图片按比例缩放示例
2014/07/01 Javascript
javascript中with()方法的语法格式及使用
2014/08/04 Javascript
JavaScript中计算网页中某个元素的位置
2015/06/10 Javascript
Bootstrap基本插件学习笔记之模态对话框(16)
2016/12/08 Javascript
Vue header组件开发详解
2018/01/26 Javascript
使用ngrok+express解决本地环境中微信接口调试问题
2018/02/26 Javascript
浅谈vue单一组件下动态修改数据时的全部重渲染
2018/03/01 Javascript
原生JavaScript实现remove()和recover()功能示例
2018/07/24 Javascript
微信小程序实现圆形进度条动画
2020/11/18 Javascript
layui table单元格事件修改值的方法
2019/09/24 Javascript
vue+iview框架实现左侧动态菜单功能的示例代码
2020/07/23 Javascript
[01:23]2014DOTA2国际邀请赛 球迷无处不在Ti现场世界杯受关注
2014/07/10 DOTA
在Python 不同级目录之间模块的调用方法
2019/01/19 Python
整理的15个非常有用的 HTML5 开发教程和速查手册
2011/10/18 HTML / CSS
英国知名衬衫品牌美国网站:Charles Tyrwhitt美国
2016/08/28 全球购物
竞选班干部演讲稿
2014/04/24 职场文书
党员干部群众路线教育实践活动个人对照检查材料
2014/09/23 职场文书
中学生社区服务活动报告
2015/02/05 职场文书