Reputation: 422
Suppose my text file is something like:
OK/INFO - 1070083 - Using waited I/O for the index and data files..
OK/INFO - 1006069 - Data cache size ==> [100000] Kbytes, [2380] data pages.
OK/INFO - 1006070 - Data file cache size ==> [0] Kbytes, [0] data file pages.
OK/INFO - 1200551 - Allocated TRIGMAXMEMSIZE: [4096] Bytes. .
OK/INFO - 1007046 - Restructuring of Database [Finstmt] Succeeded.
OK/INFO - 1007067 - Total Restructure Elapsed Time : [8.36] seconds.
OK/INFO - 1013273 - Database NA_PLN.Finstmt altered.
Now I have to search for Elapsed from this text file. If Elapsed is present print something, and if it is not present print some other quote. What i have tried is:for line in inputFile:
if 'Elapsed' in line:
print 'Present'
if 'Elapsed' not in line:
print 'Not present'
But this gives not present for nearly all the lines except for the one in which the required string is present.
Is there any way by which I can check for presence and absence and print only once??
Upvotes: 0
Views: 428
Reputation: 15204
If you want the check to be performed for the entire file and not line by line you can do it like this:
lines_in_file = open(inputFile).readlines()
test = 'Present' if any('Elapsed' in line for line in lines_in_file) else 'Not present'
print(test)
You can read more about any
here. Also note that any
is lazy meaning that it does not have to go through the whole lines_in_file
container. It will exit as soon as its predicate ('Elapsed' in line
in this case) evaluates to True
.
Upvotes: 1
Reputation: 1696
When you loop through the file line by line, the following statements will be executed for every line. What you want is some code that can basically say
if "Elapsed" in file:
print("Present")
else:
print("Not present")
Since in python the read() function reads in the file as a literal string, new line characters and all, you can implement this code as the following:
file = open("filepath.txt") #this is your file's path
text = file.read()
if "Elapsed" in text:
print("Present")
else:
print("Not present")
This saves you the trouble of looping over the file.
Upvotes: 1
Reputation: 7461
This should work:
present = False
for line in inputFile:
if 'Elapsed' in line:
present = True
break
if present:
print 'Present'
else:
print 'Not present'
Upvotes: 0
Reputation: 23084
Unless the file is very long, you can just read the entire file content into a string and test it.
>>> from pathlib import Path
>>> 'Elapsed' in Path('filename.txt').read_text()
True
Upvotes: 0
Reputation: 4279
Did you know that loops can have an else
clause?
for line in inputFile:
if 'Elapsed' in line:
print 'Present'
break
else:
print 'Not present'
This will let you know if Elapsed appears at least once in your file, which is what i understand you want to achieve
The else clause will only be called if the loop is allowed to complete, that is if "Elapsed" isn't in your file
Upvotes: 0