import re
#自定義正則 rex="\'0000-00-00 00:00:00\'" new_str='now()' old_file_path=r'C:\Users\Ths\Desktop\test.txt' new_file_path=r'C:\Users\Ths\Desktop\newtest.txt' def match_timestamp(repex,eachline): p=re.compile(repex) return p.findall(eachline) #打開舊文件,將每一行yield后作為迭代器返回。 def old_file_yield(old_file_path): with open(old_file_path,'r') as oldf: while True: line=oldf.readline() yield line if not line: oldf.close() break #打開新文件開始逐行讀取替換。 def replace_match(old_file_path,new_file_path): count=0 with open(new_file_path,"w") as newf: for line in old_file_yield(old_file_path): ifmatch=match_timestamp(rex,line) if not line:
newf.close() return count break elif ifmatch !=[]: count+=1 print("替換前:%s" % line) line=line.replace(rex,new_str) print("替換后:%s" % line) newf.write(line) else: newf.write(line) print('一共替換了%s行' % replace_match(old_file_path,new_file_path))