您的位置:首页 > 编程语言 > Python开发

python学习笔记-解决OC文件重名冲突

2016-11-01 11:46 501 查看
本人用于解决动态库第三方冲突,添加前缀,防止类名重复

#!/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_")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 前缀 OC 重名