[英]how to delete the entire line if line has specific word in python
我有一个像这样的.txt文件:
the pen is yellow
pen is yellow
hi
hello
我想删除包含“笔”字的整行
像这样:
hi
hello
我试过了
with open("myfile.txt", "r") as f:
lines = f.readlines()
with open("myfile.txt", "w") as f:
for line in lines:
if "pen" in line:
f.write(line)
- - - - - - - - - - - - - -和 - - - - - - - - - - - -------- 我如何只删除.txt 文件中的“笔”字
首先,您需要将结果放在另一个文件 (myfile2) 上,并且需要在此文件上打印不包含“pen”的行。
with open("myfile.txt", "r") as f:
lines = f.readlines()
with open("myfile2.txt", "w") as f:
for line in lines:
if "pen" not in line:
f.write(line)
else:
f.write("\n")
其次只是替换单词使用 replace(,)
with open("myfile3.txt", "w") as f:
for line in lines:
line = line.replace("pp","")
f.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.