Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading