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中使用元类的教程
Apr 28 Python
Python表示矩阵的方法分析
May 26 Python
Python编程给numpy矩阵添加一列方法示例
Dec 04 Python
python selenium 获取标签的属性值、内容、状态方法
Jun 22 Python
使用Python进行体育竞技分析(预测球队成绩)
May 16 Python
在Pycharm中使用GitHub的方法步骤
Jun 13 Python
django实现支付宝支付实例讲解
Oct 17 Python
python实现扫雷游戏
Mar 03 Python
python使用gdal对shp读取,新建和更新的实例
Mar 10 Python
基于Python脚本实现邮件报警功能
May 20 Python
python实现学生管理系统开发
Jul 24 Python
python实现过滤敏感词
May 08 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
德生PL990,目前市面上唯一一款便携式插卡蓝牙全波段高性能收音机
2021/03/02 无线电
php批量删除数据
2007/01/18 PHP
php反射应用示例
2014/02/25 PHP
PHP常用技术文之文件操作和目录操作总结
2014/09/27 PHP
php强制下载文件函数
2016/08/24 PHP
JS 实现双色表格实现代码
2009/11/24 Javascript
jQuery 树形结构的选择器
2010/02/15 Javascript
AppBaseJs 类库 网上常用的javascript函数及其他js类库写的
2010/03/04 Javascript
基于jquery实现一张图片点击鼠标放大再点缩小
2013/09/29 Javascript
jQuery实现表单步骤流程导航代码分享
2015/08/28 Javascript
jQuery实现的Tab滑动选项卡及图片切换(多种效果)小结
2015/09/14 Javascript
Boostrap模态窗口的学习小结
2016/03/28 Javascript
微信小程序 购物车简单实例
2016/10/24 Javascript
简单实现js浮动框
2016/12/13 Javascript
angularjs实现的前端分页控件示例
2017/02/10 Javascript
详解js获取video任意时间的画面截图
2019/04/17 Javascript
ES6 Set结构的应用实例分析
2019/06/26 Javascript
vue 使用插槽分发内容操作示例【单个插槽、具名插槽、作用域插槽】
2020/03/06 Javascript
[02:37]TI8勇士令状不朽珍藏II视频展示
2018/06/23 DOTA
使用Python写个小监控
2016/01/27 Python
python自动结束mysql慢查询会话的实例代码
2019/10/27 Python
python3中的logging记录日志实现过程及封装成类的操作
2020/05/12 Python
python 爬虫如何实现百度翻译
2020/11/16 Python
全面总结使用CSS实现水平垂直居中效果的方法
2016/03/10 HTML / CSS
Needle & Thread官网:英国仙女品牌
2018/01/13 全球购物
一份全面的PHP面试问题考卷
2012/07/15 面试题
银行会计业务的个人自我评价
2013/11/02 职场文书
搞笑婚礼主持词
2014/03/13 职场文书
英语三分钟演讲稿
2014/08/19 职场文书
幼儿园开学通知
2015/04/24 职场文书
转正申请报告格式
2015/05/15 职场文书
单位工作证明范本
2015/06/15 职场文书
2015年市场营销工作总结
2015/07/23 职场文书
JavaScript继承的三种方法实例
2021/05/12 Javascript
详解Java分布式事务的 6 种解决方案
2021/06/26 Java/Android
python超详细实现完整学生成绩管理系统
2022/03/17 Python