python 脚本遍历文件夹并替换字符串,支持大量文件

import os

file_path = []
def func():
    fileDir = "/Users/attackt/downloads/dictionary"
    for root, dirs, files in os.walk(fileDir):  
        for fileitem in files:
            file_path.append('{}/{}'.format(root,fileitem))

def alter(file,old_str,new_str):
    file_data = ""
    with open(file, "r") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data += line
    with open(file,"w") as f:
        f.write(file_data)
           
if __name__ == "__main__":
    func()
    for item in file_path:
        if ".html" in item:
            alter(item,"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML-full","")

 

你可能感兴趣的:(python,python,替换字符串,查找文件)