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中的字符串操作和编码Unicode详解
Jan 18 Python
利用Python查看目录中的文件示例详解
Aug 28 Python
Python竟能画这么漂亮的花,帅呆了(代码分享)
Nov 15 Python
python实现嵌套列表平铺的两种方法
Nov 08 Python
django与小程序实现登录验证功能的示例代码
Feb 19 Python
谈谈Python中的while循环语句
Mar 10 Python
pandas 缺失值与空值处理的实现方法
Oct 12 Python
python3中的logging记录日志实现过程及封装成类的操作
May 12 Python
为什么python比较流行
Jun 19 Python
Python调用C语言程序方法解析
Jul 07 Python
Python-openpyxl表格读取写入的案例详解
Nov 02 Python
pandas实现导出数据的四种方式
Dec 13 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
简单分析ucenter 会员同步登录通信原理
2014/08/25 PHP
PHP使用Pear发送邮件(Windows环境)
2016/01/05 PHP
phpstudy隐藏index.php的方法
2020/09/21 PHP
理解JavaScript中的事件
2006/09/23 Javascript
JavaScript与函数式编程解释
2007/04/27 Javascript
javascript qq右下角滑出窗口 sheyMsg
2010/03/21 Javascript
浅析Prototype的模板类 Template
2011/12/07 Javascript
jquery uploadify 在FF下无效的解决办法
2014/09/26 Javascript
javascript给span标签赋值的方法
2015/11/26 Javascript
JQuery移动页面开发之屏幕方向改变与滚屏的实现
2015/12/03 Javascript
JavaScript编码风格指南(中文版)
2016/08/26 Javascript
基于jquery实现多选下拉列表
2017/08/02 jQuery
js禁止浏览器页面后退功能的实例(推荐)
2017/09/01 Javascript
vue 计时器组件的实现代码
2017/09/14 Javascript
vuex提交state&amp;&amp;实时监听state数据的改变方法
2018/09/16 Javascript
vue-cli 2.*中导入公共less文件的方法步骤
2018/11/22 Javascript
其实你可以少写点if else与switch(推荐)
2019/01/10 Javascript
vue + typescript + video.js实现 流媒体播放 视频监控功能
2019/07/07 Javascript
微信小程序和H5页面间相互跳转代码实例
2019/09/19 Javascript
基于vue的video播放器的实现示例
2021/02/19 Vue.js
[58:29]DOTA2-DPC中国联赛 正赛 Phoenix vs XG BO3 第一场 1月31日
2021/03/11 DOTA
[50:38]DOTA2-DPC中国联赛 正赛 Phoenix vs CDEC BO3 第二场 3月7日
2021/03/11 DOTA
老生常谈python函数参数的区别(必看篇)
2017/05/29 Python
python的变量与赋值详细分析
2017/11/08 Python
python安装pywin32clipboard的操作方法
2019/01/24 Python
pycharm 如何取消连按两下shift出现的全局搜索
2021/01/15 Python
HTML5如何为形状图上颜色怎么绘制具有颜色和透明度的矩形
2014/06/23 HTML / CSS
EJB包括(SessionBean,EntityBean)说出他们的生命周期,及如何管理事务的
2015/07/24 面试题
会议开场欢迎词
2014/01/15 职场文书
2014升学宴答谢词
2014/01/26 职场文书
高中军训感言600字
2014/03/11 职场文书
政协调研汇报材料
2014/08/15 职场文书
党的群众路线教育实践活动学习计划
2014/11/03 职场文书
2015年勤工助学工作总结
2015/04/29 职场文书
2015重阳节敬老活动总结
2015/07/29 职场文书
我的中国梦心得体会范文
2016/01/05 职场文书