介绍python对文件操作实现全文或单行替换

迷茫
发布: 2017-03-25 17:17:46
原创
1226人浏览过

python修改文件时,使用w模式会将原本的文件清空/覆盖。可以先用读(r)的方式打开,写到内存中,然后再用写(w)的方式打开。

  1. 替换文本中的taste 为 tasting

Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
登录后复制
#将文件读取到内存中
with open("./fileread.txt","r",encoding="utf-8") as f:
	lines = f.readlines()  
#写的方式打开文件
with open("./fileread.txt","w",encoding="utf-8") as f_w:
	for line in lines:
		if "taste" in line:
         #替换
			line = line.replace("taste","tasting") 
		f_w.write(line)
登录后复制

2.全文中搜索替换或者单行替换

#文本内容
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
taste
taste
taste
taste
登录后复制
#定义一个函数,带有4个参数
#x 表示要更新的文件名称
#y 表示要被替换的内容
#z 表示 替换后的内容
#s 默认参数为 1 表示只替换第一个匹配到的字符串
# 如果参数为 s = 'g' 则表示全文替换
def string_switch(x,y,z,s=1):
	with open(x, "r", encoding="utf-8") as f:
	    #readlines以列表的形式将文件读出
		lines = f.readlines()

	with open(x, "w", encoding="utf-8") as f_w:
	    #定义一个数字,用来记录在读取文件时在列表中的位置
		n = 0
		#默认选项,只替换第一次匹配到的行中的字符串
		if s == 1:
			for line in lines:
				if y in line:
					line = line.replace(y,z)
					f_w.write(line)
					n += 1
					break
				f_w.write(line)
				n += 1
			#将剩余的文本内容继续输出
			for i in range(n,len(lines)):
				f_w.write(lines[i])
		#全局匹配替换
		elif s == 'g':
			for line in lines:
				if y in line:
					line = line.replace(y,z)
				f_w.write(line)
登录后复制

测试

1)默认参数 1,只替换匹配到的第一行

立即学习Python免费学习笔记(深入)”;

string_switch("fileread.txt","taste","tasting")

#结果
Yesterday when I was young
昨日当我年少轻狂
The tasting of life was sweet
生命的滋味是甜的
As rain upon my tongue
taste
taste
taste
taste
登录后复制

2)全局替换

string_switch("fileread.txt","taste","tasting","g")

#结果
Yesterday when I was young
昨日当我年少轻狂
The tasting of life was sweet
生命的滋味是甜的
As rain upon my tongue
tasting
tasting
tasting
tasting
登录后复制

以上就是介绍python对文件操作实现全文或单行替换的详细内容,更多请关注php中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号