目錄下文件快速批量替換關鍵字

使用方法:將Root修改爲壓縮包解壓後的目錄,然後填寫要替換的新舊字符串即可,最後手動壓縮一下就行:

"""
@author: Bre Athy
@contact: https://www.zhihu.com/people/you-yi-shi-de-hu-xi
@productware: PyCharm
@file: html漢化.py
@time: 2020/1/8 22:19
"""
import os

def replaceGO(path,theold,thenew):
    global a
    for f in os.listdir(path):
        f = os.path.join(path, f)
        if os.path.isfile(f):
            with open(f, "r", encoding="utf-8")as fp:
                content = fp.read()
            if content.find(theold)!=-1:
                content = content.replace(theold,thenew)
                a += 1
            if content.find(theold.encode('unicode_escape').decode())!=-1:
                content = content.replace(theold.encode('unicode_escape').decode(), thenew.encode('unicode_escape').decode())
                a += 1
            with open(f, "w", encoding="utf-8")as fp:
                fp.write(content)
        elif os.path.isdir(f):
            replaceGO(f,theold,thenew)
        else:
            print(f)


def main():
    global a
    a = 0
    Root = r"文件解壓目錄"

    theold = r"舊字符串"
    thenew = r"新字符串"
    replaceGO(Root, theold, thenew)
    print(f"【舊字符串】一共替換了 {a} 次")


if __name__ == "__main__":
    main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章