make me a python app with a gui to search for string of text in all txt files in a folder and subfolders
Assistant
User
ity needs to have a gui and a box to add folder that has txt files which cal also have subflders and a box for exact text u are looking for and then another box that has all reesults and u can click file in results box to open it
Assistant
Certainly! To create a Python application with a GUI that searches for a string of text in all .txt files within a folder and its subfolders, we can use a library like tkinter for the GUI and the os module to traverse the directory. We'll also use the re module for searching text within files. Below is a simple example of how this can be achieved:
python
import os
import re
import tkinter as tk
from tkinter import filedialog, simpledialog, messagebox
class TextSearchApp:
def __init__(self, root):
self.root = root
self.root.title("Text Search in .txt Files")
self.search_result_box = tk.Text(root, wrap='word', height=20, width=60)
self.search_result_box.pack(padx=10, pady=10)
self.search_button = tk.Button(root, text="Search Text", command=self.search_text)
self.search_button.pack(pady=5)
def search_text(self):
folder_path = filedialog.askdirectory(title="Select Folder")
if not folder_path:
messagebox.showerror("Error", "Please select a valid folder.")
return
search_string = simpledialog.askstring("Input", "Enter text to search for:")
if not search_string:
messagebox.showerror("Error", "Search string can't be empty.")
return
self.search_result_box.delete(1.0, tk.END)
matches = self.search_in_folder(folder_path, search_string)
if matches:
for match in matches:
self.search_result_box.insert(tk.END, f"{match}\n")
else:
messagebox.showinfo("Results", "No matches found.")
def search_in_folder(self, folder_path, search_string):
matches = []
for root, _, files in os.walk(folder_path):
for file in files:
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
try:
text = f.read()
for line_number, line in enumerate(text.splitlines(), 1):
if re.search(search_string, line, re.IGNORECASE):
matches.append(f"Match found in {file_path} on line {line_number}: {line.strip()}")
except Exception as e:
# Handle any exceptions reading files
self.search_result_box.insert(tk.END, f"Error reading {file_path}: {e}\n")
return matches
if __name__ == "__main__":
root = tk.Tk()
app = TextSearchApp(root)
root.mainloop()
Instructions:
Dependencies:
Ensure you have Python 3 installed.
No external dependencies are required for this example as tkinter is included with standard Python distributions.
Running the Application:
Save the above code into a file, for example, text_search_app.py.
Run the file by navigating to the directory where it's saved and executing python text_search_app.py in your terminal or command prompt.
Using the Application:
Click on "Search Text" to start the process.
A dialog will appear to select a directory to search within.
After selecting the directory, you'll be prompted to enter the string you want to search.
The application will search for the provided string in all .txt files inside the chosen directory and its subfolders.
The results will be displayed in the text box in the application's window.
This code searches for text efficiently in .txt files and displays the file path, line number, and content where the text is found. Adjustments can be made to improve user interface elements or extend functionality.
To create a more advanced version of the application you want, we will enhance the graphical user interface to include distinct entry fields for specifying the folder path and the search text. Additionally, we'll implement functionality to open files directly from the results. Here's the code to achieve this:
python
import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox
import webbrowser
class TextSearchApp:
def __init__(self, root):
self.root = root
self.root.title("Text Search in .txt Files")
# Frame for folder path entry and button
folder_frame = tk.Frame(root)
folder_frame.pack(pady=5, padx=10, fill=tk.X)
self.folder_path_var = tk.StringVar()
self.folder_entry = tk.Entry(folder_frame, textvariable=self.folder_path_var, width=50)
self.folder_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.browse_button = tk.Button(folder_frame, text="Browse...", command=self.browse_folder)
self.browse_button.pack(side=tk.LEFT, padx=5)
# Entry for the search string
search_frame = tk.Frame(root)
search_frame.pack(pady=5, padx=10, fill=tk.X)
tk.Label(search_frame, text="Search Text: ").pack(side=tk.LEFT)
self.search_text_var = tk.StringVar()
self.search_entry = tk.Entry(search_frame, textvariable=self.search_text_var, width=50)
self.search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
# Search button
self.search_button = tk.Button(root, text="Search", command=self.search_text)
self.search_button.pack(pady=5)
# Listbox for results
self.results_listbox = tk.Listbox(root, width=80, height=20)
self.results_listbox.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.results_listbox.bind('<Double-Button-1>', self.open_file)
def browse_folder(self):
folder_path = filedialog.askdirectory(title="Select Folder")
if folder_path:
self.folder_path_var.set(folder_path)
def search_text(self):
folder_path = self.folder_path_var.get().strip()
search_string = self.search_text_var.get().strip()
if not folder_path or not search_string:
messagebox.showerror("Error", "Both folder and search string must be provided.")
return
self.results_listbox.delete(0, tk.END)
matches = self.search_in_folder(folder_path, search_string)
if matches:
for match in matches:
self.results_listbox.insert(tk.END, match)
else:
messagebox.showinfo("Results", "No matches found.")
def search_in_folder(self, folder_path, search_string):
matches = []
for root, _, files in os.walk(folder_path):
for file in files:
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
try:
text = f.read()
for line_number, line in enumerate(text.splitlines(), 1):
if re.search(re.escape(search_string), line):
display_path = f"{file_path} - line {line_number}"
matches.append(display_path)
except Exception as e:
# Handle any exceptions reading files
display_path = f"Error reading {file_path}: {e}"
matches.append(display_path)
return matches
def open_file(self, event):
selected_index = self.results_listbox.curselection()
if selected_index:
selected_item = self.results_listbox.get(selected_index).split(" - ", 1)[0]
try:
webbrowser.open(f'file://{os.path.abspath(selected_item)}')
except Exception as e:
messagebox.showerror("Error", f"Unable to open file: {e}")
if __name__ == "__main__":
root = tk.Tk()
app = TextSearchApp(root)
root.mainloop()
Enhancements Made:
Folder Path Entry and Browse Button:
Added an entry widget and a "Browse" button to select the folder containing .txt files.
Search Text Entry:
Added an entry widget for users to input the exact text they want to search for.
Results Listbox:
Used a Listbox to display search results, showing the file path and line number where the search text is found.
File Opening:
Implemented double-click functionality on the listbox items to open the respective file in the default text editor.
Instructions:
Setup:
Make sure you have Python 3 installed on your system.
Save the code above to a file, for example, text_search_app.py.
Running the App:
Run the application using python text_search_app.py.
Usage:
Click "Browse..." to select a directory.
Enter the text you wish to search for in the "Search Text" input box.
Click "Search" to find all matches.
Double-click any result to open the corresponding file in your default text editor or viewer.
This program allows easy navigation and interaction with files, enhancing the overall usability and functionality of the search process.