-3

I've tried numerous ways and sometimes it get the last known match, sometimes it just stops at the first, and sometimes it never works at all. My goal is to find every matching word within a phrase and print EACH PHRASE if true. I tried doing something like this(PSUEDO'ISH)-Do not judge code it's merely the best example I could think of as I typed:

f = open("dognames.txt", "r")
key = "Bob" 
if key in f:
    print line

Dog names being in text file:

Bob
Bobby
Kitty
Bobbel
Boaban
Cat

Output should be:

Bob
Bobby
Bobbel
smac89
  • 39,374
  • 15
  • 132
  • 179
Naval
  • 25
  • 8
  • If you Google the phrase "How to read a Python file", you’ll find resources that can explain it much better than we can in an answer here. – Prune Dec 14 '18 at 19:05
  • Possible duplicate of [Python: Filter lines from a text file which contain a particular word](https://stackoverflow.com/questions/5245058/python-filter-lines-from-a-text-file-which-contain-a-particular-word) – trincot Dec 14 '18 at 20:40

1 Answers1

3

Close, but you forgot to loop over the lines

f = open("dognames.txt", "r")
key = "Bob" 
for line in f:
    if key in line:
        print line

Furthermore, you want to make sure that the file is closed after you use it, so use this format which essentially creates a context for the file and allows the file to close itself after execution leaves the scope of the with statement.

with open("dognames.txt", "r") as f:
    key = "Bob" 
    for line in f:
        if key in line:
            print line
smac89
  • 39,374
  • 15
  • 132
  • 179
  • 1
    I figured out the issue and unfortunately this will probably get me a slap in the face. The expected outcome was wrong because I wanted a NOT IN. Not a IN Line. I know I didn't explain that in the original post but the goal was just see an example of iterating over each line by line just to ensure I tried the idiomatic ways of doing things. THANK YOU! – Naval Dec 14 '18 at 19:36