user2696225
user2696225

Reputation: 379

Python3: Finding a phrase (string) in a file

I am a bit confused and hoping you can help....

My overall task is to determine whether a .txt file contains the line '**** Optimisation achieved ****'. If it does, make opt = 'Y'. Otherwise don't do anything other than close the file.

I have looked at this question, but am having a little trouble with some of the answers:
I define the function test() such that when it is called I pass the phrase to be searched for and the filename to it. Within test() I open the file and number the lines in it.

def test(phrase, filename):
    with open(filename, 'r') as f:
         for num, line in enumerate (f,1):

it is at this point that I am having issues and am a little confused. The following is based on the answer given by @Dr jimbob and uses if phrase in f:, and returns N:

            if phrase in f:
                return 'Y'
            else:
                return 'N'

opt = test('****Optimisation achieved ****', file.txt)
print(opt)

[N.B. The same occurs if I skip the line in which the lines of the file are numbered]

However, if I use the following which is based on the answer given by @suzanshakya and uses if phrase in line: and returns Y:

            if phrase in line:
                return 'Y'
            else:
                return 'N'

opt = test('****Optimisation achieved ****', file.txt)
print(opt)

I have used the same .txt file for both, and it definitely contains the line ****Optimisation achieved****.

As the first is more akin to what I want to do, any prods in the right direction would be gratefully received - although I ask patience as my programming is quite basic

Upvotes: 0

Views: 191

Answers (1)

wwii
wwii

Reputation: 23743

If you do not need line numbers, you do not need to use enumerate().

This function will read the entire file into text then search through text to see if phrase is in it.

def test(phrase, filename):
    phrase = phrase.strip()
    with open(filename, 'r') as f:
        text = f.read()
    if phrase in text:
        return 'Y'
    else:
        return 'N'

This function reads the file line by line (iterates over the file) and returns 'Y' if it finds phrase in a line. If it reaches the end of the file, it returns 'N'.

def test(phrase, filename):
    phrase = phrase.strip()
    with open(filename, 'r') as f:
        for line in f:
            if phrase in line:
                return 'Y'
        return 'N'

Either will work.

  • The first may have a speed advantage because it only accesses the file once and searching for the phrase is done in memory.
  • The second has the advantage of keeping the memory footprint small.

Upvotes: 2

Related Questions