0

I have to write a function which can search a txt file for a phrase then print every line that contains the phrase.

def find_phrase(filename,phrase):
    for line in open(filename):
        if phrase in line: 
            print line,

That is what I have at the moment and it only prints the first instance.

Bach
  • 6,145
  • 7
  • 36
  • 61
  • This should work. Are you sure you have more than one matching (case-sensitive) line? Also: Use a with statement so you can automatically close the file when you are done. – ramcdougal Apr 02 '14 at 10:33
  • It works for me with a simple example file. Can you show us the file you are using? – Germano Apr 02 '14 at 10:34
  • It worked for me too. Can you post an output example of your code? – Tengis Apr 02 '14 at 10:34

2 Answers2

1

I have tried your code with a sample script, which goes like this

#sample.py

import sys
print "testing sample"
sys.exit() 

when i run your script,

find_phrase('sample.py','sys')

It prints,

import sys
sys.exit(). 

If this is not your intended output, please share the file you are using.

rajpython
  • 179
  • 2
  • 3
  • 14
0

Below is the pythonic approach. The with statement will safely open the file and handle closing the file when it is done. You can also open multiple files with the "with" statement. How to open a file using the open with statement

def print_found_lines(filename, phrase):
    """Print the lines in the file that contains the given phrase."""
    with open(filename, "r") as file:
        for line in file:
            if phrase in line:
                print(line.replace("\n", ""))
    # end with (closes file automatically)
# end print_found_lines
Community
  • 1
  • 1
justengel
  • 6,132
  • 4
  • 26
  • 42