How to keep lines which contains specific string and remove other lines from .txt file?

Question:

How to keep lines which contains specific string and remove other lines from .txt file?

Example: I want to keep the line which has word "hey" and remove others.

test.txt file:

first line

second one

heyy yo yo

fourth line

Code:

keeplist = ["hey"]
with open("test.txt") as f:
    for line in f:
        for word in keeplist:
Asked By: Karim Mostafa

||

Answers:

Its hard to remove lines from a file. Its usually better to write a temporary file with the desired content and then change that to the original file name.

import os

keeplist = ["hey"]
with open("test.txt") as f, open("test.txt.tmp", "w") as outf:
    for line in f:
        for word in keeplist:
            if word in line:
                outf.write(line)
                break
os.rename("test.txt.tmp", "test.txt")
Answered By: tdelaney
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.