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))