Create a Personal Knowledge Base That Searches Notes Instantly in Python
Build a lightweight personal knowledge base with JSON storage and instant case-insensitive full-text search across note titles and content.
Python code
47 linesimport json
import re
import sys
class PersonalKnowledgeBase:
def __init__(self, file_path="kb_notes.json"):
self.file_path = file_path
self.notes = self._load_notes()
def _load_notes(self):
try:
with open(self.file_path, "r") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def _save_notes(self):
with open(self.file_path, "w") as f:
json.dump(self.notes, f, indent=2)
def add_note(self, title, content):
self.notes[title] = content
self._save_notes()
def search(self, query):
query_lower = query.lower()
results = {}
for title, content in self.notes.items():
if (query_lower in title.lower() or
query_lower in content.lower()):
results[title] = content
return results
if __name__ == "__main__":
kb = PersonalKnowledgeBase()
kb.add_note("Python tips", "Use pathlib for file paths, not os.path.")
kb.add_note("Flask setup", "Install Flask with pip, define routes.")
kb.add_note("Git commands", "git commit -m, git push origin main")
query = "git"
found = kb.search(query)
if found:
print(f"Found {len(found)} note(s) for '{query}':")
for title, content in found.items():
print(f" {title}: {content}")
else:
print(f"No notes found for '{query}'.")
Output
Found 1 note(s) for 'git':
Git commands: git commit -m, git push origin main
How it works
The class uses a JSON file as persistent storage, loading and saving notes with the standard library's json module. The search method performs a case-insensitive substring match on both titles and content by converting the query and note fields to lowercase. The try-except block handles missing or corrupted files on startup, returning an empty dictionary as a fallback. This design keeps dependencies minimal and the knowledge base portable with zero configuration.
Common mistakes
- Forgetting to call `_save_notes()` after adding a note, so changes are lost on exit.
- Assuming the JSON file is always present – the fallback handles missing files but not permission errors.
- Using case-sensitive matching, which misses notes when query casing doesn't match.
- Overwriting the entire JSON file on every save – fine for small note sizes but not large-scale use.
Variations
- Use SQLite via the standard `sqlite3` module for faster queries on large note collections.
- Add keyword tagging and a `filter_by_tag` method for categorized search.
Real-world use cases
- A developer saving daily code snippets with a quick CLI to find them later.
- A student curating lecture notes that need instant lookup during exam prep.
- A technical writer maintaining a local glossary of terms and seeing searchable results in a terminal.
Sponsored
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert CSV Files to JSON in Python easy
- Convert Image to ASCII Art in Python medium
Keep learning
Related tutorials and quizzes for this topic.