Search code examples
pythonfiletxt

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


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:

Solution

  • 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")