Anki Core Library

25.9.2 · active · verified Sun Apr 12

The `anki` package is the Python backend library for the Anki desktop flashcard application. It provides the core data models, collection management, and scheduling logic. It is primarily used for developing Anki add-ons or for advanced programmatic interaction with Anki's internal database. This is not a high-level library for generating Anki decks from scratch (for that, consider `genanki`). It tracks the Anki desktop application's versioning and has a release cadence tied to the desktop app updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to open an existing Anki collection database and retrieve basic information about it. It requires the path to a `collection.anki2` file, which is typically found within your Anki profile folder. Ensure Anki desktop is not running when accessing the database directly to prevent locking issues or data corruption.

import os
from anki.collection import Collection
from anki.errors import DBError

# NOTE: This example requires an existing Anki collection database.
# If you don't have one, create a dummy profile in Anki desktop.
# Replace 'path/to/your/collection.anki2' with the actual path.
# On Linux/macOS: ~/.local/share/Anki2/User 1/collection.anki2
# On Windows: %APPDATA%\Anki2\User 1\collection.anki2
collection_path = os.environ.get('ANKI_COLLECTION_PATH', 'collection.anki2') # Placeholder/default

try:
    # Connect to the collection
    col = Collection(collection_path)

    # Example: Print some collection statistics
    print(f"Collection path: {col.path}")
    print(f"Total notes: {col.note_count()}")
    print(f"Total cards: {col.card_count()}")

    # Example: Get the first 5 notes
    note_ids = col.find_notes("nid:*")[:5]
    for nid in note_ids:
        note = col.get_note(nid)
        print(f"  Note ID: {note.id}, Model: {note.model()['name']}, Tags: {note.tags}")

    # Close the collection (important to avoid database locking/corruption)
    col.close()

except DBError as e:
    print(f"Error opening or interacting with Anki collection: {e}")
    print("Please ensure the ANKI_COLLECTION_PATH environment variable is set correctly and Anki is not running.")
except FileNotFoundError:
    print(f"Collection database not found at '{collection_path}'.")
    print("Please ensure the ANKI_COLLECTION_PATH environment variable points to a valid Anki collection.anki2 file.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →