python实现的用于搜索文件并进行内容替换的类实例
作者:不吃皮蛋 发布时间:2022-01-07 13:50:43
标签: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"
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程序设计有所帮助。


猜你喜欢
- 一、导言导语:在计算机进行数据交换时,常常会有一个进制转换的过程,我们知道计算机只认0 和 1.在内存系统中,基本基于二进制进行运算的,但是
- 随着ES6规范的到来,Js中定义变量的方法已经由单一的 var 方式发展到了 var、let、const 三种之多。var 众所周知,可那俩
- 前言最近公司项目从vue2迁移到vue3,感觉自己对Object.defineProperty和Proxy的了解还是在浅尝辄止的地步,所以今
- CSS的学习和其他的学习一样,都需要特定的方法才能比较快的去掌握它.要想掌握CSS, 首先要学会HTML,我刚开始是从零开始学习的
- 处理数据时我们经常需要从数组中随机抽取元素,这时候我们可以考虑使用np.random.choice()函数语法格式numpy.random.
- Oracle数据库以其高可靠性、安全性、可兼容性,得到越来越多的企业的青睐。如何使Oracle数据库保持优良性能,这是许多数据库管理员关心的
- 本文实例讲述了Python多层装饰器用法。分享给大家供大家参考,具体如下:前言Python 的装饰器能够在不破坏函数原本结构的基础上,对函数
- system函数 说明:执行外部程序并显示输出资料。 语法:string system(string command, int [retur
- 最近做一个的GUI,因为调用了os模块里的system方法,使用pyinstaller打包的时候选择不输出系统命令弹框,程序无法运行,要求要
- 在pytest自动化测试中,如果只是简单的从应用的角度来说,完全可以不去了解pytest中的显示信息的部分以及原理,完全可以通过使用推荐的p
- 为了优化OceanBase的query timeout设置方式,特调研MySQL关于timeout的处理,记录如下。 mysql> s
- 升级到第二版,开一贴以示庆贺,哈哈哈 自 Ver1.1 升级内容 1. 增加函数列表 2. 增加函数
- 本文介绍了webpack编译vue项目生成的代码探索,分享给大家,具体如下:前言往 main.js 里写入最简单的 vue 项目结构如下im
- (一)关于体验约瑟夫.派恩和詹姆士.吉尔摩在《体验经济》一书中提出其观点:所谓“体验”就是企业以商品为道具,以服务为舞台,以顾客为中心,创造
- Python 使用 selenium 进行自动化测试 或者协助日常工作,内容如下所示:1、基础准备需要准备 Python 环境需要安装 se
- 用法:DataFrame.drop(labels=None,axis=0, index=None, columns=None, inplac
- 本文实例为大家分享了python给心爱的人每天发天气预报的具体代码,供大家参考,具体内容如下下面的代码实现了用了之前获取天气的代码,然后用i
- 设置AccessCount字段可以根据需求在特定的时间范围内如果是相同IP访问就在AccessCount上累加。Create table C
- MySQL报错:错误代码: 1293 Incorrect table definition; there can be only one T
- 本文为大家分享了python实现外卖信息管理系统的具体代码,供大家参考,具体内容如下一、需求分析 需求分析包含如下:1、问题描述 以外卖信息