genanki

raw JSON →
0.13.1 verified Sat May 09 auth: no python

A library for generating Anki decks programmatically. Current version 0.13.1, supports Anki 2.1+ (via .apkg), requires Python 3.6+. Releases are infrequent; API is stable.

pip install genanki
error ModuleNotFoundError: No module named 'genanki'
cause Package not installed; or virtual environment not activated.
fix
Run: pip install genanki
error ValueError: Model ID 1607392319 is already used by another model in this deck.
cause Reusing a Model ID that conflicts with an existing one in the same deck (or across decks).
fix
Use a unique ID for each model, e.g., import random; model_id = random.randrange(1<<30, 1<<31)
error TypeError: write_to_file() missing 1 required positional argument: 'filename'
cause Forget to pass filename to write_to_file; it's a method, not a property.
fix
package.write_to_file('deck.apkg')
gotcha Model IDs and Deck IDs must be unique and not collide with existing IDs in Anki. Use random large integers (e.g., from time-based generators) to avoid conflicts.
fix Use a random 10-digit integer or a timestamp-based ID: genanki.Deck(int(time.time()*1000), 'Deck Name')
gotcha The .apkg file is a ZIP archive. If you need to modify it, you must rebuild the deck from scratch; genanki does not support appending to existing decks.
fix Regenerate the entire deck programmatically instead of trying to edit the .apkg directly.
gotcha Media files (images, audio) must be added via Package.media_files before writing. Simply linking in the note fields is not enough.
fix package = genanki.Package(deck); package.media_files = ['image.jpg']

Creates a simple Anki deck with one card and writes it to output.apkg.

import genanki

# Define a model (card template)
my_model = genanki.Model(
  1607392319,
  'Simple Model',
  fields=[
    {'name': 'Question'},
    {'name': 'Answer'},
  ],
  templates=[
    {
      'name': 'Card 1',
      'qfmt': '{{Question}}',
      'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
    },
  ])

# Create a deck with a unique ID
deck = genanki.Deck(
  2059400110,
  'My Deck')

# Add notes (cards) to the deck
note = genanki.Note(
  model=my_model,
  fields=['Capital of France?', 'Paris'])
deck.add_note(note)

# Generate .apkg file
package = genanki.Package(deck)
package.write_to_file('output.apkg')

print('Deck generated successfully!')