python实现替换某个文件中的某个字符串(全部替换)

时间:2022-12-02 14:13:04
#!/usr/bin/python
#-*-coding:utf-8-*-
import click
#不需要替换的文件
UNMATCH = (".DS_Store","loading","niutou_run","zhuyao")
#参数设置
@click.command()
@click.option("-root",help=u'根目录')
@click.option("-src",help=u'源字符')
@click.option("-dst",help=u'目标字符')

def run(**options):
root = options["root"]
src = options["src"]
dst = options["dst"]
for file in os.listdir(root):
colorPrint("file:",file)
if not isInTuple(file):
jsonName = file + ".json"
fileFullPath = root +"/" + file + "/" + jsonName
fp = open(fileFullPath,"r+")
tempStr = fp.read()
result = re.sub(src,dst,tempStr)
colorPrint("seek1:",fp.tell())
fp.seek(0,0)
colorPrint("seek2:",fp.tell())
fp.write(result)
fp.close()
#是否在UNMATCH中
def isInTuple(name):
for temp in UNMATCH:
if name == temp:
return True
break
return False
#彩色打印
def colorPrint(desc,str):
print('\033[1;31;40m')
print(desc,str)
print('\033[0m')
if __name__ == '__main__':
run()