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

 

转载于:https://www.cnblogs.com/lalalaxixixi/p/10861919.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值