如何删除整个行,如果行有特定的词在python

cclgggtu  于 2022-12-17  发布在  Python
关注(0)|答案(1)|浏览(94)

我有这样一个.txt文件:

the pen is yellow
pen is yellow
    hi
hello

并且我想要删除包含“pen”单词的整行
像这样:

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文件中的“pen”单词
hof1towb

hof1towb1#

首先您需要将结果放到另一个文件(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)

相关问题