![]() |
L'evoluzione del nostro tool di ricerca locale continua ๐(se ti sei perso le puntante precedenti puoi dare un occhio qui e qui).
In questa puntata vedremo come integrare la funzionalitร di ricerca nel contenuto dei file ๐ (e non solo nel nome del file).
Obiettivo
L’obiettivo di questa evoluzione del tool รจ estendere la ricerca al contenuto del file in modo da individuare la parola chiave da ricercare non solo nel nome del file o delle cartelle ma anche all'interno del testo dei file.
Dobbiamo quindi dare all’utente la possibilitร di scegliere come eseguire la ricerca:
-
Solo nel nome (file + cartelle) — comportamento attuale del tool realizzato nei precedenti articoli
-
Nel contenuto dei file — oltre alla ricerca nel nome, il programma deve aprire i file e cercare nel loro contenuto
L’estensione รจ completamente trasparente all’utente: basta inserire un nome e il programma cerca ovunque, in cartelle, file e contenuto dei file.
Codice
import os
import time
import subprocess
import platform
# -----------------------------
# OPEN FOLDER
# -----------------------------
def open_folder(path):
system = platform.system()
if system == "Windows":
os.startfile(path)
elif system == "Darwin": # macOS
subprocess.Popen(["open", path])
else: # Linux
subprocess.Popen(["xdg-open", path])
# -----------------------------
# OPEN FILE
# -----------------------------
def open_file(path):
system = platform.system()
if system == "Windows":
os.startfile(path)
elif system == "Darwin": # macOS
subprocess.Popen(["open", path])
else: # Linux
subprocess.Popen(["xdg-open", path])
# -----------------------------
# MAIN LOOP
# -----------------------------
while True:
root = input("Search in (or type 'exit' to quit): ").strip()
if root.lower() == "exit":
print("Program terminated.")
break
if not os.path.isdir(root):
print("Invalid path.\n")
continue
name = input("Search term (file/folder name or content): ").strip()
if name.lower() == "exit":
print("Program terminated.")
break
# -----------------------------
# CHOOSE SEARCH MODE
# -----------------------------
print("\nChoose search mode:")
print("1) Search only in file/folder NAMES")
print("2) Search also inside FILE CONTENTS")
while True:
mode = input("> ").strip()
if mode in ("1", "2"):
break
print("Invalid choice. Type 1 or 2.")
search_in_content = (mode == "2")
print("\nSearching...")
start_time = time.time()
found_paths = [] # files + folders
found_files = [] # only files (for opening later)
found_folders = [] # only folders (actual folders found)
# -----------------------------
# SEARCH EXECUTION
# -----------------------------
for path, dirs, files in os.walk(root):
# ---- SEARCH IN FOLDER NAMES ----
for dirname in dirs:
if name.lower() in dirname.lower():
folder_path = os.path.join(path, dirname)
found_paths.append(folder_path)
found_folders.append(folder_path)
print("๐ Found folder:", folder_path)
# ---- SEARCH IN FILE NAMES ----
for filename in files:
if name.lower() in filename.lower():
file_path = os.path.join(path, filename)
found_paths.append(file_path)
found_files.append(file_path)
print("๐ Found file:", file_path)
# ---- SEARCH IN FILE CONTENTS (optional) ----
if search_in_content:
for filename in files:
file_path = os.path.join(path, filename)
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
if name.lower() in line.lower():
if file_path not in found_paths:
found_paths.append(file_path)
found_files.append(file_path)
print("๐ Found in content:", file_path)
break
except:
pass
duration = time.time() - start_time
print(f"\nSearch completed in {duration:.3f} seconds.")
if not found_paths:
print("No results found.\n")
continue
# -----------------------------
# UNIQUE FOLDERS FOR THE FINAL MENU
# -----------------------------
unique_folders = set()
for p in found_paths:
if os.path.isdir(p):
unique_folders.add(p) # actual folder found
else:
unique_folders.add(os.path.dirname(p)) # parent folder of file
unique_folders = sorted(unique_folders)
found_files = sorted(found_files)
# -----------------------------
# FINAL MENU FOR OPENING ITEMS
# -----------------------------
while True:
print("\nWould you like to open something?")
print("1) Open a folder")
print("2) Open a file")
print("no) Continue to new search\n")
choice = input("> ").strip().lower()
if choice == "no":
print("")
break
# ---- OPEN FOLDERS ----
if choice == "1":
print("\n=== FOLDERS ===")
for i, folder in enumerate(unique_folders, 1):
print(f"{i}) ๐ {folder}")
sel = input("\nChoose a folder number (or 'no'): ").strip()
if sel.lower() == "no":
continue
if sel.isdigit():
index = int(sel)
if 1 <= index <= len(unique_folders):
folder = unique_folders[index - 1]
print("Opening:", folder)
open_folder(folder)
else:
print("Invalid number.")
continue
# ---- OPEN FILES ----
if choice == "2":
if not found_files:
print("No files available to open.")
continue
print("\n=== FILES ===")
for i, file in enumerate(found_files, 1):
print(f"{i}) ๐ {file}")
sel = input("\nChoose a file number (or 'no'): ").strip()
if sel.lower() == "no":
continue
if sel.isdigit():
index = int(sel)
if 1 <= index <= len(found_files):
file = found_files[index - 1]
print("Opening:", file)
open_file(file)
else:
print("Invalid number.")
continue
print("Invalid choice.")
Esempio di Output
Choose search mode:
1) Search only in file/folder NAMES
2) Search also inside FILE CONTENTS
> 2
Searching...
๐ Found file: C:\Users\Example\Desktop\project.txt
๐ Found file: C:\Users\Example\Desktop\project.xlsx
๐ Found in content:C:\Users\Example\Desktop\MasterPlan.pptx
๐ Found folder: C:\Users\Example\Desktop\Project
Search completed in 5.237 seconds.
Would you like to open something?
1) Open a folder
2) Open a file
no) Continue to new search
> 2
=== FILES ===
1) ๐ C:\Users\Example\Desktop\project.txt
2) ๐ C:\Users\Example\Desktop\project.xlsx
3) ๐ C:\Users\Example\Desktop\MasterPlan.pptx
Choose a file number (or 'no'): 1
Opening: C:\Users\Example\Desktop\project.txt
๐ Cosa fa ora il programma?
✔ Ricerca nei nomi dei file
✔ Ricerca nei nomi delle cartelle
✔ Opzionale: ricerca anche nel contenuto dei file
✔ Mostra liste separate:
๐ cartelle che matchano direttamente
๐ cartelle che contengono file trovati
✔ Evita duplicati
✔ Mantiene tutte le funzionalitร di apertura cartelle
✔ Evita errori su file binari o troppo grandi
Conclusione
Grazie a questa nuova feature, il tool ora รจ in grado di fare ricerche a 360° — un pรฒ come faremmo con Windows ma in maniera molto piร veloce.
Buona ricerca ๐!
Follow me #techelopment
Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment
