用幾行python程式碼實現大量文字檔案裡的文字替換
阿新 • • 發佈:2020-10-14
""" 用python進行大量文字替換。 因為工作需要,有時候我們需要替換大量文字檔案裡的特定文字,用python可以幫我們非常簡單快速的處理。 其中最下面的if語句,當輸入'html'時, 會查詢當前目錄及所有子目錄下包含'html'的所有檔案 檔案裡的 智閱薈 將會被替換為 智慧之家 """ # coding=gbk import os def search(a b): for file in os.listdir(a): if os.path.isfile(a + '\\' + file): if b in file: # print(file '=>' a + '\\' + file) tofilename=a+'\\'+file print(tofilename) replace(tofilename) else: search(a + '\\' + file b) def replace(filename): num=0 with open(filename "r" encoding='utf-8') as f: lines = f.readlines() # 寫的方式開啟檔案 with open(filename "w" encoding='utf-8') as f_w: for line in lines: if "智閱薈" in line: # 替換 line = line.replace("智閱薈","智慧之家") num = num + 1 f_w.write(line) print("替換完成:" + str(num) + "個") if __name__ == "__main__":
#下一行html表示是所有的網頁檔案 search(os.path.abspath('.') 'html')
原始碼檔案可在微信公眾號”智閱薈“回覆112下載:
↑關注上方公眾號回覆 112即可下載↑
最通俗的解讀,最深刻的乾貨,最簡潔的教程,眾多你不知道的小技巧等你來發現!
歡迎關注公眾號:「智閱薈」,懂技術,更懂你!