简体   繁体   English

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

[英]how to delete the entire line if line has specific word in python

i have a.txt file like this:我有一个像这样的.txt文件:

the pen is yellow
pen is yellow
    hi
hello

and i want to delete the entire line that include "pen" word我想删除包含“笔”字的整行

like this:像这样:



    hi
hello

and i tried this我试过了

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)

---------------------------AND------------------------------ how i delete just the "pen" word in the.txt file - - - - - - - - - - - - - -和 - - - - - - - - - - - -------- 我如何只删除.txt 文件中的“笔”字

First you need to put the result on another file (myfile2) and you need to print on this file the lines thats not contain "pen".首先,您需要将结果放在另一个文件 (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")

Second to just substitute the word use replace(,)其次只是替换单词使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM