简体   繁体   中英

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

i have a.txt file like this:

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

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".

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(,)

with open("myfile3.txt", "w") as f:
    for line in lines:
        line = line.replace("pp","")
        f.write(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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