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中endswith()函数的基本使用
Apr 07 Python
Python中使用platform模块获取系统信息的用法教程
Jul 08 Python
Python 中 list 的各项操作技巧
Apr 13 Python
Python进阶学习之特殊方法实例详析
Dec 01 Python
用Python将一个列表分割成小列表的实例讲解
Jul 02 Python
Python3.6使用tesseract-ocr的正确方法
Oct 17 Python
python根据list重命名文件夹里的所有文件实例
Oct 25 Python
python 利用for循环 保存多个图像或者文件的实例
Nov 09 Python
flask session组件的使用示例
Dec 25 Python
python基于itchat模块实现微信防撤回
Apr 29 Python
python多线程共享变量的使用和效率方法
Jul 16 Python
pytorch 中forward 的用法与解释说明
Feb 26 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 Ajax中文乱码问题解决方法
2009/02/27 PHP
PHP 简单数组排序实现代码
2009/08/05 PHP
探讨:如何使用PHP实现计算两个日期间隔的年、月、周、日数
2013/06/13 PHP
PHP代码审核的详细介绍
2013/06/13 PHP
php对二维数组按指定键值key排序示例代码
2013/11/26 PHP
php关联数组快速排序的方法
2015/04/17 PHP
php实现的redis缓存类定义与使用方法示例
2017/08/09 PHP
PHP实现的微信公众号扫码模拟登录功能示例
2019/05/30 PHP
laravel中Redis队列监听中断的分析
2020/09/14 PHP
FireFox JavaScript全局Event对象
2009/06/14 Javascript
jQuery实现购物车数字加减效果
2015/03/14 Javascript
JavaScript中Number.MAX_VALUE属性的使用方法
2015/06/04 Javascript
基于javascript实现页面加载loading效果
2020/09/15 Javascript
JS中BOM相关知识点总结(必看篇)
2016/11/22 Javascript
jQuery操作DOM_动力节点Java学院整理
2017/07/04 jQuery
老生常谈js中的MVC
2017/07/25 Javascript
JavaScript中Require调用js的实例分享
2017/10/27 Javascript
使用nodejs+express实现简单的文件上传功能
2017/12/27 NodeJs
vue项目如何刷新当前页面的方法
2018/05/18 Javascript
layui(1.0.9)文件上传upload,前后端的实例代码
2019/09/26 Javascript
Javascript前端下载后台传来的文件流代码实例
2020/08/18 Javascript
Python的一些用法分享
2012/10/07 Python
Python基础教程之if判断,while循环,循环嵌套
2019/04/25 Python
Python学习笔记之变量、自定义函数用法示例
2019/05/28 Python
Python计算两个矩形重合面积代码实例
2019/09/16 Python
Tensorflow 实现将图像与标签数据转化为tfRecord文件
2020/02/17 Python
详解python环境安装selenium和手动下载安装selenium的方法
2020/03/17 Python
PyCharm 2020.2下配置Anaconda环境的方法步骤
2020/09/23 Python
天美时手表加拿大官网:Timex加拿大
2016/09/01 全球购物
JD Sports比利时官网:英国领先的运动鞋和运动服饰零售商
2018/10/10 全球购物
杭州-DOTNET笔试题集
2013/09/25 面试题
共产党员批评与自我批评
2014/10/15 职场文书
2016年大学生寒假社会实践心得体会
2015/10/09 职场文书
维护民族团结心得体会2016
2016/01/15 职场文书
品德与社会教学反思
2016/02/24 职场文书
MySQL 8.0 驱动与阿里druid版本兼容问题解决
2021/07/01 MySQL