python读取文件并替换字段_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() # 关闭文件

1301d4d8c45b60157dc8309ab139ea86.png

5a4a1d550cff8e0143d27f3b80f5b44a.png

以上这篇python 读取文件并替换字段的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易采站长站。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值