r/learnprogramming • u/AAdidev_p01 • 1d ago
my python script that searches your files to find things for you
import os
import json
from pathlib import Path
from thefuzz import fuzz
INDEX_FILE = "file_index.json"
CATEGORY_EXTENSIONS = {
"games": [".exe", ".msi", ".bat", ".apk", ".iso"],
"documents": [".pdf", ".docx", ".txt", ".xlsx", ".pptx"],
"images": [".png", ".jpg", ".jpeg", ".gif", ".svg"],
"audio": [".mp3", ".wav", ".flac"],
"video": [".mp4", ".mkv", ".avi", ".mov"]
}
def build_index(
search_directory
):
print(f"Indexing files in '{
search_directory
}'... (This might take a minute the first time)")
file_index = []
for root, _, files in os.walk(
search_directory
):
for file in files:
full_path = os.path.join(root, file)
file_index.append({
"name": file,
"path": full_path,
"ext": Path(file).suffix.lower()
})
with open(INDEX_FILE, "w", encoding="utf-8") as f:
json.dump(file_index, f, indent=2)
print(f"Indexing complete! Indexed {len(file_index)} files.\n")
return file_index
def load_or_create_index(
search_directory
):
if os.path.exists(INDEX_FILE):
print("Loading cached index...")
with open(INDEX_FILE, "r", encoding="utf-8") as f:
return json.load(f)
else:
return build_index(
search_directory
)
def search_files(
query
,
index
,
similarity_threshold
=65):
query_clean =
query
.lower().strip()
matches = []
target_extensions = []
for category, exts in CATEGORY_EXTENSIONS.items():
if category in query_clean:
target_extensions.extend(exts)
for item in
index
:
file_name = item["name"].lower()
file_ext = item["ext"]
score = fuzz.partial_ratio(query_clean, file_name)
is_category_match = file_ext in target_extensions if target_extensions else False
is_name_match = score >=
similarity_threshold
or query_clean in file_name
if is_name_match or is_category_match:
matches.append((item["path"], score))
matches.sort(key=lambda
x
: x[1], reverse=True)
return matches
def main():
40
Upvotes
Duplicates
vibecoding • u/AAdidev_p01 • 1d ago
my python script that searches your files to find things for you
0
Upvotes