Я пытаюсь выполнить поиск по всему файлу во всех подкаталогах моего корневого каталога, чтобы вывести строки, содержащие «ключевые_фразы», которые вводит пользователь.Мой текущий код может найти и вывести строки для большинства файлов в моих подкаталогах, но я не могу найти строки в определенных файлах папки, почти как если бы они были невидимы для поиска.Ниже приведен мой код для функции python и Tkinter GUI для пользователя, чтобы ввести каталог и ключевые фразы.Графический интерфейс Tkinter только для справки, я считаю, что проблема в цикле for моей функции Python.
Моя функция Python
import os
def searchandOutput(rootdir, keyPhrases):
path = rootdir # Enter the root directory you want to search from
key_phrases = [keyPhrases] # Enter here the key phrases in the lines you hope to find
key_phrases = [i.replace('\n','') for i in key_phrases] #In case an "\n" is added to the end of the string when the parameter is passed to the function
# This for loop allows all sub directories and files to be searched
for (path, subdirs, files) in os.walk(path):
files = [f for f in os.listdir(path) if f.endswith('.txt') or f.endswith('.log')] # Specify here the format of files you hope to search from (ex: ".txt" or ".log")
#files = [f for f in files if f.endswith('.txt') or f.endswith('.log')]
files.sort() # file is sorted list
files = [os.path.join(path, name) for name in files] # Joins the path and the name, so the files can be opened and scanned by the open() function
# The following for loop searches all files with the selected format
for filename in files:
# Opens the individual files and to read their lines
with open(filename) as f:
f = f.readlines()
# The following loop scans for the key phrases entered by the user in every line of the files searched, and stores the lines that match into the "important" array
for line in f:
for phrase in key_phrases:
if phrase in line:
print(line)
break
print("The end of the directory has been reached, if no lines are printed then that means the key phrase does not exist in the root directory you entered.")
Мой графический интерфейс TKinter
from searchandOutput import searchandOutput
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class Feedback:
def __init__(self, master):
master.title('Search and Output')
master.resizable(False, False)
master.configure(background = '#ffffff')
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
self.style = ttk.Style()
self.style.configure('TFrame', background = '#ffffff')
self.style.configure('TButton', background = '#ffffff')
self.style.configure('TLabel', background = '#ffffff', font = ('Arial', 11))
ttk.Label(self.frame_header, wraplength = 300, text = "Output the desired lines from the logs in the directory by entering the following.").grid(row = 0, column = 1)
self.frame_content = ttk.Frame(master)
self.frame_content.pack()
ttk.Label(self.frame_content, text = 'Root Directory:').grid(row = 0, column = 0, pady = 4)
#ttk.Label(self.frame_content, text = 'Applicable File Types:').grid(row = 1, column = 0)
ttk.Label(self.frame_content, text = 'Key Phrase:').grid(row = 2, column = 0)
self.entry_rootdirectory = ttk.Entry(self.frame_content, width = 35, font = ('Arial', 10))
self.text_keyphrase = Text(self.frame_content, width = 35, height = 5, font = ('Arial', 10))
#self.text_filetypes = Text(self.frame_content, width = 35, height = 5, font = ('Arial', 10))
self.entry_rootdirectory.grid(row = 0, column = 1)
#self.text_filetypes.grid(row = 1, column = 1)
self.text_keyphrase.grid(row = 2, column = 1)
ttk.Button(self.frame_content, text = 'Submit', command = self.submit).grid(row = 5, column = 0, pady = 5)
ttk.Button(self.frame_content, text = 'Clear', command = self.clear).grid(row = 5, column = 1, pady = 5)
def submit(self):
#Enter code that connects to the python script here
rootd = self.entry_rootdirectory.get()
keyp = self.text_keyphrase.get(1.0, 'end')
searchandOutput(rootd, keyp)
messagebox.showinfo(title = "Search Requested", message = "Search Completed!")
def clear(self):
self.entry_rootdirectory.delete(0, 'end')
#self.text_filetypes.delete(1.0, 'end')
self.text_keyphrase.delete(1.0, 'end')
def main():
root = Tk()
feedback = Feedback(root)
root.mainloop()
if __name__ == "__main__": main()