Python文件操作:实现单行与全文字符串替换的方法
本文介绍在Python中修改文件内容时,如何避免直接覆盖原文件导致数据丢失。通过先读取文件至内存列表,再根据需求对特定行或全文进行字符串替换,最后写回文件。文章提供了默认只替换首行匹配内容及全局替换两种模式的函数实现,适用于需要精准控制替换范围的文本处理场景。
在Python中修改文件内容时,若直接使用写(w)模式打开文件,原有的文件内容会被清空或覆盖。为确保数据安全,建议先以读(r)模式打开文件,将内容读取至内存中,随后再以写(w)模式打开文件进行写入操作。
示例目标:将文本中的单词“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)
接下来演示如何在全文中进行搜索替换,或者仅对单行进行替换操作。
#文本内容 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时,仅替换匹配到的第一行内容。
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基础文件操作中实现全文或单行替换的方法分享到此结束,希望能为读者提供有益参考,并欢迎大家继续支持本站获取更多技术内容。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













