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()  # 关闭文件

这里写图片描述

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值