python按行读取并替换


 
fp = open(''test2.txt','w') #打开你要写得文件test2.txt lines = open('test1.txt').readlines() #打开文件,读入每一行 for s in lines: fp.write( s.replace('love','hate').replace('yes','no')) # replace是替换,write是写入 fp.close() # 关闭文件
import os import re f_path = r'c:\a.txt' f = open (f_path, "r+") open('c:\\test.txt', 'w').write(re.sub(r'hello world', 'Love python', f.read()))

原文: 
参考备忘,指针这个没明白什么意思,找时间验证下

#写在原文件中 fp3=open("file3.txt","r+") #不用w w会清空数据 s=fp3.read()#读出 fp3.seek(0,0) #指针移到头 原来的数据还在是替换 会存在一个问题 如果少 会替换不了全部数据,自已思考解决! #从头写入 fp3.write(s.replace("hello","good")) fp3.close() 
import os
os.chdir('D:\\') # 跳到D盘 if not os.path.exists('test1.txt'): # 看一下这个文件是否存在 exit(-1) #不存在就退出 lines = open('test1.txt').readlines() #打开文件,读入每一行 fp = open(''test2.txt','w') #打开你要写得文件test2.txt for s in lines: # replace是替换,write是写入 fp.write( s.replace('love','hate').replace('yes','no')) fp.close() # 关闭文件

这里写图片描述

这里写图片描述


免责声明!

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



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