Skip to content
Advertisement

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement