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