Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/shengpeng3344/article/details/52994455
I used to resolve conflicts third-party dynamic libraries, add a prefix to prevent duplicate class name
#!/user/bin/python
# -*- coding:UTF-8 -*-
import os
import fileinput
def prefixFiles(path,prefix):
#修改当前目录下全部文件的前缀 - 不包括子文件夹
list = []
files = os.listdir(path) # 路径可以自己
flag = True;
for name in files:
suffix = ['.m', '.cpp', '.h', '.mm']
a = os.path.splitext(name)
if a[1] in suffix:
tmpStr = a[0]
if tmpStr.startswith(prefix, 0, 4): #如果包含prefix
tup = (name[len(prefix):name.find('.')], name[0:name.find('.')])
list.append(tup)
else:
if name.find("+") != -1: #分类文件处理
pass
else:
newname = prefix + a[0] + a[1]
if flag:
os.chdir(path)
flag = False
tup = (name[0:name.find('.')], newname[0:newname.find('.')])
list.append(tup)
os.rename(name, newname)
return list
def prefixAllFiles(path,prefix):
#修改当前目录及子目录下文件
list = []
list.extend(prefixFiles(path,prefix))
for root, dirs, files in os.walk(path):
list.extend(prefixFiles(root,prefix))
for tmp in list: #去除重复
while list.count(tmp) > 1:
list.remove(tmp)
return list
def replaceSingleDirectory(filepath,tuple):
files = os.listdir(filepath)
for name in files:
suffix = ['.m', '.cpp', '.h', '.mm']
a = os.path.splitext(name)
if a[1] in suffix:
for tmp in tuple:
path = os.path.join(filepath, name)
print (path, tmp[0], tmp[1])
os.chdir(filepath)
# replaceText2(name,tmp[0], tmp[1])
replaceText(path, tmp[0], tmp[1])
def replaceMutableDirectory(path,tuple):
replaceSingleDirectory(path,tuple)
for root, dirs, files in os.walk(path):
replaceSingleDirectory(root,tuple)
def replaceText(filepath,oldtext,newtext):
tmp = fileinput.input(filepath,inplace=1)
tmp.nextfile()
for line in tmp:
# print fileinput.lineno()
if judgeIsOCdefine(line,oldtext,newtext):
line = line.replace(oldtext,newtext)
print line.strip("\n")
else:
print line.strip("\n")
def judgeIsOCdefine(str,oldtext,newtext):
if str.find(oldtext) != -1 and str.find(newtext) == -1 :
if len(str) <= len(oldtext):
return False
tmp = str[str.find(oldtext) + len(oldtext):str.find(oldtext) + len(oldtext) + 1]
if tmp == " ":
return True
elif tmp == ":":
return True
elif tmp == ";":
return True
elif tmp == ")":
return True
elif tmp == "*":
return True
elif tmp == ".":
return True
elif tmp == ">":
return True
elif tmp == ",":
return True
else:
if str.find("@implementation") != -1:
return True
elif str.find("@interface") != -1:
return True
else:
return False
def replaceText2(name,oldtext,newtext):
with open(name, "r+") as f:
d = f.read()
d.replace(oldtext, newtext)
f.write(d)
def renameOC(path,prefix):
tupList = prefixAllFiles(path, prefix) #tuplist (oldname,newname)
replaceMutableDirectory(path, tupList)
print "success"
# find_file_text(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\src','mainCRTStartup')
path = raw_input("请输入文件夹路径:").strip()
renameOC(path,"HX_")