分享

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

 乙甲壬 2020-07-06
#!/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()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多