I have a file with logs. each log is located in a line. I created a function that searching the file and looking for each log as a string. I ordered the logs i wish to look for as an array / list. Currently, the function is returning true/false according to the first item in the list. for example, if i will delete item #2 which is log #2 from the file, the function will still return true because item #1 is in the file. I wish that my loop will keep run until all the items in list were searched. this is my implementation:
def isClassDomainPassed():
with open(NR_log, 'r') as logfile:
key1 = 'The application is in Class Domain tab'
key2 = 'Inspection Sampling is open'
key3 = 'Golden Image was chosen'
key4 = 'Accurate Navigation was chosen'
key5 = 'Golden Image is enabled with Accurate Navigation'
key6 = 'Location was added to Inspection Locations List'
key7 = 'All dies were added to Inspection Dies List'
keys = [key1, key2, key3, key4, key5, key6, key7]
for key in keys:
for num, line in enumerate(logfile, 1):
if key in line:
return True, print("fine")
return False, print("not")
isClassDomainPassed()
CodePudding user response:
You can't loop through the file multiple times unless you seek back to the beginning each time. Switch the order of the loops. Then you can also replace the key in keys
loop with any()
.
The False
return should be outside the loop, so you only do it if you make it through all the loops.
for line in logfile:
if any(key in line for key in keys):
print("fine")
return True
print("not")
return False
CodePudding user response:
If I understand you correctly, you want to check if all keys are included in the logfile. If yes, the function should return True
:
def isClassDomainPassed(file_name):
with open(file_name, "r") as logfile:
data = logfile.read()
key1 = "The application is in Class Domain tab"
key2 = "Inspection Sampling is open"
key3 = "Golden Image was chosen"
key4 = "Accurate Navigation was chosen"
key5 = "Golden Image is enabled with Accurate Navigation"
key6 = "Location was added to Inspection Locations List"
key7 = "All dies were added to Inspection Dies List"
keys = [key1, key2, key3, key4, key5, key6, key7]
return all(k in data for k in keys)
print(isClassDomainPassed("sample.txt"))