替换文件夹下所有文件中的字符串。
#coding=utf8
from os import chdir, getcwd, listdir, path
import codecs
import re
def excuepath(folder_path, blacklist, extends):
chdir(folder_path)
cwd=getcwd()
dirs=listdir(cwd)
for tmp in dirs:
# 排除blacklist文件夹
if tmp not in blacklist:
fpath=path.join(cwd, tmp)
if path.isfile(fpath):
print('fpath=',fpath)
# 只extends的文件类型
if fpath.split('.')[-1] in extends:
data = ""
with codecs.open(fpath, "r", "utf-8") as rfile:
data = rfile.read()
with codecs.open(fpath, "w", "utf-8") as wfile:
replace_times = 0
for item in mapping_string:
replace_times += data.count(item[0])
data = data.replace(item[0], item[1]);
print(r'替换次数:', replace_times)
print()
wfile.write(data)
#如果是文件夹,递归
elif path.isdir(fpath):
excuepath(fpath)
def load_replace_keys(key_path):
mapping_string=[]
with codecs.open(key_path, "r", "utf-8") as rfile:
for item in rfile.readlines():
mapping_string.append(item.split())
return mapping_string
if __name__=='__main__':
# 替换的键值对,一行两个字符串,前面的是旧字符串,后面的是新字符串,中间用空格隔开
key_path = './replace.keys.txt'
# 待替换文件的 文件夹目录,会递归检索文件,并替换文件中所有的字符串
folder_path = r"D:\workspace\Payment_WebApp_JIBU\ibupay-web\src\main\resources"
# 只匹配下面的文件类型
extends = ['ftl', 'js']
# 排除哪些文件夹
blacklist = ['.history', 'dest', 'libs']
mapping_string = load_replace_keys(key_path)
excuepath(folder_path, blacklist, extends)