1. 程式人生 > >Python(69)_寫函式,實現修改檔案內容

Python(69)_寫函式,實現修改檔案內容

#-*-coding:utf-8-*-
import os
'''
寫函式,使用者傳入修改的檔名,與修改的內容
執行函式,完成整個檔案的批量修改操作
'''
def func(filename,old,new):
    with open(filename,encoding='utf-8') as f,open('%s.bak'%filename,'w',encoding='utf-8') as f2:
        for line in  f:
            if old in line:
                line = line.replace(old,new)
         
#寫檔案 f2.write(line) os.remove(filename) os.replace('%s.bak'%filename,filename) func('log.txt','bowen','Love')