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解析xml模块封装代码
Feb 07 Python
浅谈python socket函数中,send与sendall的区别与使用方法
May 09 Python
python技能之数据导出excel的实例代码
Aug 11 Python
python多进程实现进程间通信实例
Nov 24 Python
获取python的list中含有重复值的index方法
Jun 27 Python
详解python如何在django中为用户模型添加自定义权限
Oct 15 Python
在python里从协程返回一个值的示例
Feb 19 Python
Python解析json代码实例解析
Nov 25 Python
python递归调用中的坑:打印有值, 返回却None
Mar 16 Python
如何搭建pytorch环境的方法步骤
May 06 Python
Python脚本实现Zabbix多行日志监控过程解析
Aug 26 Python
Pycharm常用快捷键总结及配置方法
Nov 14 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
Uncaught exception com_exception with message Failed to create COM object
2012/01/11 PHP
浅谈discuz密码加密的方式
2014/05/22 PHP
PHP的拦截器实例分析
2014/11/03 PHP
php实现图片转换成ASCII码的方法
2015/04/03 PHP
静态html文件执行php语句的方法(推荐)
2016/11/21 PHP
php使用imagecopymerge()函数创建半透明水印
2018/01/25 PHP
Laravel创建数据库表结构的例子
2019/10/09 PHP
3Z版基于jquery的图片复选框(asp.net+jquery)
2010/04/12 Javascript
javascript Array.prototype.slice使用说明
2010/10/11 Javascript
jQuery中queue()方法用法实例
2014/12/29 Javascript
jQuery选择器querySelector的使用指南
2015/01/23 Javascript
JS实现图片放大镜效果的方法
2015/02/27 Javascript
JavaScript实现给按钮加上双重动作的方法
2015/08/14 Javascript
jquery制作属于自己的select自定义样式
2015/11/23 Javascript
JavaScript File API文件上传预览
2016/02/02 Javascript
JQuery用户名校验的具体实现
2016/03/18 Javascript
Bootstrap table使用方法详细介绍
2016/12/09 Javascript
微信小程序 图片边框解决方法
2017/01/16 Javascript
基于 Bootstrap Datetimepicker 联动
2017/08/03 Javascript
详解vue中点击空白处隐藏div的实现(用指令实现)
2018/04/19 Javascript
Python2中的raw_input() 与 input()
2015/06/12 Python
使用python实现rsa算法代码
2016/02/17 Python
python dict.get()和dict['key']的区别详解
2016/06/30 Python
Django1.9 加载通过ImageField上传的图片方法
2018/05/25 Python
Python对HTML转义字符进行反转义的实现方法
2019/04/28 Python
python 多线程对post请求服务器测试并发的方法
2019/06/13 Python
Win10下python 2.7与python 3.7双环境安装教程图解
2019/10/12 Python
CK澳大利亚官网:Calvin Klein澳大利亚
2020/12/12 全球购物
工程专业求职自荐书范文
2014/02/18 职场文书
水电站项目建议书
2014/05/12 职场文书
高中教师考核方案
2014/05/18 职场文书
四风自我剖析材料思想汇报
2014/10/01 职场文书
党支部创先争优公开承诺书
2015/04/30 职场文书
地道战观后感2000字
2015/06/04 职场文书
仓库管理制度范本
2015/08/04 职场文书
SpringCloud Feign请求头删除修改的操作代码
2022/03/20 Java/Android