My goal is to use multiple functions to search for strings in a log.
I am running into an issue where only the 1st function called after opening the file retrieves the entire contents of the file. All other functions do not retrieve any contents of the open file.
For testing I used a simple file with the following text:
aaa this is line 1
bbb this is line 2
ccc this is line 3
ddd this is line 4
eee this is line 5
fff this is line 6
ggg this is line 7
This is the section of my code that is the problem.
def main():
with open('myinputfile.txt', 'r') as myfile:
get_aaa(myfile)
get_bbb(myfile)
get_fff(myfile)
Each get_xxx function simply searches for a string. get_aaa() searches for ^aaa, get_bbb() searches for ^bbb, and get_fff() searches for ^fff. If the string is found the function prints some text along with the matching line. If the string is not found a "NOT FOUND" message is printed.
When running the script I receive this output:
Start Date: aaa this is line 1
ITEM BBB: NOT FOUND
ITEM FFF: NOT FOUND
When I modify the main() and reordering to call get_bbb() before get_aaa() I receive this output:
Start Time: bbb this is line 2
ITEM AAA: NOT FOUND
ITEM FFF: NOT FOUND
Based on this testing I am sure only the 1st function called after opening the file is reading the entire contents of file.
For additional testing I found if I open the file prior to calling each function - I receive the expected output.
def main():
with open('myinputfile.txt', 'r') as myfile:
get_aaa(myfile)
with open('myinputfile.txt', 'r') as myfile:
get_bbb(myfile)
with open('myinputfile.txt', 'r') as myfile:
get_fff(myfile)
myfile.close(
Results in the expected output.
Start Date: aaa this is line 1
Start Time: bbb this is line 2
UserId : fff this is line 6
Any hints on how I can open a file once and search the contents of the file using multiple functions?