I am writing a python program to search the data on the text file in GUI
The search function normally gives the result (in CLI). I want to use it with Tkinter, but when I pull the input with the Tkinter Entry function, my search function does not work.
Whatever I write, it outputs the data in the entire text file. I think the problem is in the if msg.get() in line:
The search function is below.
JavaScript
x
11
11
1
def search():
2
with open(r"loglar.txt", 'r') as fp:
3
for l_no, line in enumerate(fp):
4
lineNum = l_no + 1
5
# search string
6
if msg.get() in line:
7
lineNumber = ('Line Number:', lineNum)
8
lineWord = ('Line:', line)
9
print(lineNumber)
10
print(lineWord)
11
Also this is my Tkinter Function
JavaScript
1
6
1
def getInfo():
2
msg = entry.get()
3
print(type(msg))
4
print(msg)
5
search()
6
Advertisement
Answer
JavaScript
1
51
51
1
def parse_date(date_str):
2
# format mm/dd/yy HH:MM:SS[.NNNNNN]
3
date_fmt = '%m/%d/%y %H:%M:%S'
4
if '.' in date_str:
5
date_fmt += '.%f'
6
return datetime.strptime(date_str, date_fmt)
7
8
9
10
11
12
13
#function to search string in text
14
def search(msg, startingDate, endingDate, beforeLine, varBefore):
15
# clear current result
16
text.delete('1.0', 'end')
17
with open('OAM.log', 'r', encoding='latin1') as fp:
18
global l_no
19
for l_no, line in enumerate(fp, 1):
20
if msg and msg not in line:
21
# does not contain search message, skip it
22
continue
23
if startingDate or endingDate:
24
# get the timestamp
25
timestamp = parse_date(line[1:25])
26
# within startingDate and endingDate ?
27
if startingDate and timestamp < startingDate:
28
# before given starting date, skip it
29
continue
30
if endingDate and timestamp > endingDate:
31
# after given ending date, skip it
32
continue
33
34
# insert the log
35
text.insert('end', ' n ')
36
text.insert('end', f'Line Number: {l_no} Log: {line}')
37
text.insert('end', ' n ')
38
39
40
41
def getInfo():
42
msg = edit.get() if var1.get() == 1 else None
43
startingDate = parse_date(tarih1.get()) if var2.get() == 1 else None
44
endingDate = parse_date(tarih2.get()) if var3.get() == 1 else None
45
afterLine = afterEntry.get() if varAfter.get() == 1 else None
46
beforeLine = beforeEntryVar.get() if varBefore.get() == 1 else None
47
afterLine = afterEntry.get() if varAfter.get() == 1 else None
48
49
50
search(msg, startingDate, endingDate, beforeLine, afterLine)
51