Python 文件操作删除指定行的实现方法
本文介绍在 Python 中如何读取文件内容并删除包含特定字符串的行。通过遍历文件行列表,利用 continue 语句跳过目标行,再将剩余内容写入新文件,从而实现行删除功能。
实现该功能的核心思路是利用 continue 语句跳过本次写入循环。
#文本内容 Yesterday when I was young 昨日当我年少轻狂 The tasting of life was sweet 生命的滋味是甜的 As rain upon my tongue tasting I lived by night and shunned the naked light of day tasting123 And only now I see how the time ran away tasting tasting
具体目标是删除文本中内容为 tasting123 的行。
with open("fileread.txt","r",encoding="utf-8") as f:
lines = f.readlines()
#print(lines)
with open("fileread.txt","w",encoding="utf-8") as f_w:
for line in lines:
if "tasting123" in line:
continue
f_w.write(line)
以上关于 Python 文件操作删除某行的示例分享完毕,供读者参考。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













