python:读取文件并替换字段

来源:互联网 发布:一键卸妆 知乎 编辑:程序博客网 时间:2024/06/05 02:35
fp = open(''test2.txt','w')  #打开你要写得文件test2.txtlines = open('test1.txt').readlines()  #打开文件,读入每一行for s in lines:fp.write( s.replace('love','hate').replace('yes','no'))    # replace是替换,write是写入fp.close()  # 关闭文件
import osimport  ref_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 osos.chdir('D:\\')       # 跳到D盘if not os.path.exists('test1.txt'): # 看一下这个文件是否存在exit(-1)                         #不存在就退出lines = open('test1.txt').readlines()  #打开文件,读入每一行fp = open(''test2.txt','w')  #打开你要写得文件test2.txtfor s in lines:# replace是替换,write是写入fp.write( s.replace('love','hate').replace('yes','no'))    fp.close()  # 关闭文件

这里写图片描述

这里写图片描述
参考资料:
https://zhidao.baidu.com/question/450489912.html
http://blog.csdn.net/liangrui1988/article/details/49539137

0 0
原创粉丝点击