python实现的用于搜索文件并进行内容替换的类实例
本文实例讲述了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程序设计有所帮助。

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

DeepSeekAPI接入与调用详解:快速上手指南本文将详细指导您如何接入和调用DeepSeekAPI,助您轻松使用强大的AI模型。第一步:获取API密钥访问DeepSeek官方网站,点击右上角的“开放平台”。您将获得一定数量的免费Tokens(用于计量API使用量)。在左侧菜单中,点击“APIKeys”,然后点击“创建APIkey”。为您的APIkey命名(例如,“test”),并立即复制生成的密钥。请务必妥善保存此密钥,因为它只会显示一次

本文深入探讨了币安(Binance)、欧易(OKX)和芝麻开门(Gate.io)三大交易所的量化交易功能,旨在帮助量化交易者选择合适的平台。文章首先介绍了量化交易的概念、优势及挑战,并阐述了优秀量化交易软件应具备的功能,例如API支持、数据源、回测工具和风控功能等。随后,对三家交易所的量化交易功能进行了详细对比分析,分别指出了它们的优劣势,最终给出了针对不同经验水平的量化交易者的平台选择建议,并强调了风险评估和策略回测的重要性。 无论您是新手还是经验丰富的量化交易者,本文都将为您提供有价值的参

DeepSeek深度学习库Python调用指南DeepSeek是一个功能强大的深度学习库,可用于构建和训练各种神经网络模型。本文将详细介绍如何使用Python调用DeepSeek进行深度学习开发。使用Python调用DeepSeek的步骤1.安装DeepSeek确保已安装Python环境和pip工具。使用以下命令安装DeepSeek:pipinstalldeepseek2.导入DeepSeek库在Python脚本或JupyterNotebook中导入DeepSeek库:impor

安币Alpha是币安平台上为专业交易者和投资者提供的工具和服务聚合平台。它的核心功能包括:1.策略广场,汇集不同交易策略;2.策略构建器,允许自定义交易策略;3.高级数据分析,提供市场分析工具;4.机构级服务,满足专业投资者的需求。

截至2024年,支持通过交易终端直接发送期权对冲指令的主流加密货币交易所有:1. Deribit,支持Delta对冲、Gamma Scalping等高级策略,提供网页版/API一键对冲;2. OKX,支持波动率对冲和策略组合工具,网页端/APP内置对冲面板;3. Binance,支持保护性对冲,需手动或API组合仓位;4. CME,提供标准期权,需通过经纪商接入;5. LedgerX,提供专业级对冲工具,需机构认证。

在LAMP架构下整合Node.js或Python服务许多网站开发者都面临这样的问题:已有的LAMP(Linux Apache MySQL PHP)架构网站需要...

基于字符集和层数生成排列组合本文将探讨如何根据给定的字符集和层数,生成相应的排列组合结果,避免重复...
