Advertisement
Najeebsk

SEARCH-FILES.pyw

Nov 27th, 2024
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.48 KB | None | 0 0
  1. import os
  2. import tkinter as tk
  3. from tkinter import ttk, messagebox
  4. from tkinter import filedialog
  5.  
  6. class FileSearchApp(tk.Tk):
  7.     def __init__(self):
  8.         super().__init__()
  9.         self.title("Najeeb Advanced File/Folder Searcher")
  10.         self.geometry("900x600")
  11.         self.configure(bg="#2e3f4f")  # Background color
  12.  
  13.         # Variables
  14.         self.search_query = tk.StringVar()
  15.         self.selected_drive = tk.StringVar(value="Select All Drives")
  16.         self.detected_drives = self.get_drives()
  17.  
  18.         # Create widgets
  19.         self.create_widgets()
  20.  
  21.     def get_drives(self):
  22.         """Detect all available drives on the system."""
  23.         drives = []
  24.         for drive in range(ord('A'), ord('Z') + 1):
  25.             drive_letter = f"{chr(drive)}:"
  26.             if os.path.exists(drive_letter):
  27.                 drives.append(drive_letter)
  28.         return ["Select All Drives"] + drives
  29.  
  30.     def create_widgets(self):
  31.         # Drive Selection Frame
  32.         drive_frame = tk.Frame(self, bg="#2e3f4f")
  33.         drive_frame.pack(pady=10)
  34.  
  35.         # Drive Dropdown
  36.         tk.Label(drive_frame, text="Select Drive:", fg="white", bg="#2e3f4f", font=("Times New Roman", 14)).pack(side=tk.LEFT, padx=5)
  37.         self.drive_dropdown = ttk.Combobox(drive_frame, textvariable=self.selected_drive, values=self.detected_drives, state="readonly", width=20)
  38.         self.drive_dropdown.pack(side=tk.LEFT, padx=5)
  39.  
  40.         # Search Field
  41.         #search_frame = tk.Frame(self, bg="#2e3f4f")
  42.         #search_frame.pack(pady=10)
  43.  
  44.         tk.Label(drive_frame, text="Enter File/Folder Name:", fg="white", bg="#2e3f4f", font=("Times New Roman", 14)).pack(side=tk.LEFT, padx=5)
  45.         self.search_entry = tk.Entry(drive_frame, textvariable=self.search_query, width=32, font=("Times New Roman", 14))
  46.         self.search_entry.pack(side=tk.LEFT, padx=5)
  47.  
  48.         # Buttons (Search, Open, Save Results, Clear) in one line
  49.         button_frame = tk.Frame(self, bg="#2e3f4f")
  50.         button_frame.pack(pady=10)
  51.  
  52.         button_style = {"bg": "#007acc", "fg": "white", "font": ("Times New Roman", 14), "width": 17, "relief": tk.RAISED}
  53.  
  54.         self.search_button = tk.Button(button_frame, text="Search Files/Folders", command=self.search_files, **button_style)
  55.         self.search_button.pack(side=tk.LEFT, padx=5)
  56.  
  57.         self.open_file_button = tk.Button(button_frame, text="Open Selected Item", command=self.open_selected_file, **button_style)
  58.         self.open_file_button.pack(side=tk.LEFT, padx=5)
  59.  
  60.         self.save_button = tk.Button(button_frame, text="Save Results", command=self.save_results, **button_style)
  61.         self.save_button.pack(side=tk.LEFT, padx=5)
  62.  
  63.         self.clear_button = tk.Button(button_frame, text="Clear Results", command=self.clear_results, **button_style)
  64.         self.clear_button.pack(side=tk.LEFT, padx=5)
  65.  
  66.         # File Listbox
  67.         self.result_frame = tk.Frame(self, bg="#2e3f4f")
  68.         self.result_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
  69.  
  70.         self.file_listbox = tk.Listbox(self.result_frame, selectmode=tk.SINGLE, width=100, height=25, bg="#1c2833", fg="white", font=("Courier New", 10))
  71.         self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  72.  
  73.         # Scrollbars
  74.         scrollbar_vertical = tk.Scrollbar(self.result_frame, orient="vertical", command=self.file_listbox.yview)
  75.         self.file_listbox.config(yscrollcommand=scrollbar_vertical.set)
  76.         scrollbar_vertical.pack(side=tk.RIGHT, fill="y")
  77.  
  78.     def search_files(self):
  79.         """Search files and folders based on the search query."""
  80.         self.file_listbox.delete(0, tk.END)  # Clear previous results
  81.         query = self.search_query.get().strip().lower()
  82.  
  83.         if not query:
  84.             messagebox.showwarning("Input Required", "Please enter a file or folder name to search.")
  85.             return
  86.  
  87.         selected_drive = self.selected_drive.get()
  88.         drives_to_search = self.detected_drives[1:] if selected_drive == "Select All Drives" else [selected_drive]
  89.  
  90.         matching_items = []
  91.  
  92.         # Traverse drives and collect matching files and folders
  93.         for drive in drives_to_search:
  94.             if os.path.exists(drive):
  95.                 for root, dirs, files in os.walk(drive):
  96.                     # Include hidden files and folders
  97.                     items = dirs + files
  98.                     for item in items:
  99.                         if query in item.lower():
  100.                             item_path = os.path.join(root, item)
  101.                             matching_items.append(item_path)
  102.                             self.file_listbox.insert(tk.END, item_path)
  103.                             self.update_idletasks()  # Keep GUI responsive
  104.  
  105.         # Show a message if no items are found
  106.         if not matching_items:
  107.             messagebox.showinfo("Search Complete", f"No files or folders found containing '{query}' in {selected_drive}.")
  108.  
  109.     def open_selected_file(self):
  110.         """Open the selected file or folder with the default program."""
  111.         selected_item_index = self.file_listbox.curselection()
  112.         if not selected_item_index:
  113.             messagebox.showwarning("No Selection", "Please select a file or folder to open.")
  114.             return
  115.  
  116.         selected_item = self.file_listbox.get(selected_item_index[0])
  117.         try:
  118.             os.startfile(selected_item)  # Open with default program
  119.         except Exception as e:
  120.             messagebox.showerror("Error Opening Item", str(e))
  121.  
  122.     def save_results(self):
  123.         """Save the search results to a file."""
  124.         if self.file_listbox.size() == 0:
  125.             messagebox.showwarning("No Results", "No results to save.")
  126.             return
  127.  
  128.         file_path = filedialog.asksaveasfilename(
  129.             defaultextension=".txt",
  130.             filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
  131.             title="Save Results As"
  132.         )
  133.         if not file_path:
  134.             return
  135.  
  136.         try:
  137.             with open(file_path, "w", encoding="utf-8") as file:
  138.                 for item in self.file_listbox.get(0, tk.END):
  139.                     file.write(item + "\n")
  140.             messagebox.showinfo("Success", f"Results saved to {file_path}")
  141.         except Exception as e:
  142.             messagebox.showerror("Error Saving Results", str(e))
  143.  
  144.     def clear_results(self):
  145.         """Clear the results from the Listbox."""
  146.         self.file_listbox.delete(0, tk.END)
  147.  
  148. if __name__ == "__main__":
  149.     app = FileSearchApp()
  150.     app.mainloop()
  151.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement