Mike Dwyer
Mike Dwyer

Reputation: 11

Extracting certain lines from a text file

So I have a text file from which I am trying to extract certain lines which contain a specific word. The lines are want are lines which contain the word HEIGHT, however there is another category in my text file called AVERAGEHEIGHT. So when I run this code it extracts all lines that contain both HEIGHT and AVERAGEHEIGHT, where as I am only interested in HEIGHT. Is there a way to fix this?

Here is my line of code for this

open('height.txt','w').writelines([ line for line in open("Test1.txt") if "HEIGHT" in line])

Thanks in advance for any advice on the matter.

Upvotes: 1

Views: 2139

Answers (2)

dmitryro
dmitryro

Reputation: 3506

You can do it like this:

with open('linestoread.txt') as f:
    our_lines = f.readlines()
    for l in our_lines:
        if 'HEIGHT' in l and not 'AVERAGEHEIGHT' in l: 
                with open('height.txt', 'a') as f:
                     f.writelines(l)

Upvotes: 1

Brian
Brian

Reputation: 1667

The simplest way I can think of, without knowing the rest of your input, would be as follows:

open('height.txt','w').writelines([ line for line in open("Test1.txt") if "HEIGHT" in line and "AVERAGEHEIGHT" not in line])

EDIT:

open('height.txt','w').writelines([ line for line in open("Test1.txt") if "HEIGHT" in line and "AVERAGEHEIGHT" not in line and "TOTAL HEIGHT" not in line])

Upvotes: 1

Related Questions