python实现逐行替换超大文件中的字符串


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM