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