1

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.

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

4 Comments

This makes perfect sense however it is not completely working for me. In reality there are two categories which I want to avoid (AVERAGEHEIGHT and TOTAL HEIGHT), and it is only working for AVERAGEHEIGHT and not TOTAL HEIGHT for some reason... strange
You never mentioned the restriction with TOTAL HEIGHT, see my edit
Yea even with that it is not recognizing it, I have copied it exactly as it is from the text file but it is still showing up, I do appreciate you trying to help though, thanks again.
Could you please post the file you're using, so that I can get a better idea of what you mean.
1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.