Can I create an Anki deck from a .CSV file?

The desktop Anki version will allow you to import "Text separated by tabs or semicolons." Use this option to choose your CSV file. After opening the file, you will be presented with a dialog which allows you to customize how your data is imported. One of the settings is an option that lets you choose the delimiter. Change this to a comma, and it should work for you.

Screenshot: Importing a CSV file into Anki


Another way to generate .apkg files is by programmatically reusing the desktop version with Python. Extend:

PYTHONPATH=/usr/share/anki: python ...

Then you can adapt the following example to your needs:

import anki
from anki.exporting import AnkiPackageExporter

collection = anki.Collection(os.path.join(TMPDIR, 'collection.anki2'))

deck_id = collection.decks.id(FBASENAME + "_deck")
deck = collection.decks.get(deck_id)

model = collection.models.new(FBASENAME + "_model")
model['tags'].append(FBASENAME + "_tag")
model['did'] = deck_id
model['css'] = """
.card {
  font-family: arial;
  font-size: 20px;
  text-align: center;
  color: black;
  background-color: white;
}
.from {
  font-style: italic;
}
"""

collection.models.addField(model, collection.models.newField('en'))
collection.models.addField(model, collection.models.newField('ru'))

tmpl = collection.models.newTemplate('en -> ru')
tmpl['qfmt'] = '<div class="from">{{en}}</div>'
tmpl['afmt'] = '{{FrontSide}}\n\n<hr id=answer>\n\n{{ru}}'
collection.models.addTemplate(model, tmpl)
tmpl = collection.models.newTemplate('ru -> en')
tmpl['qfmt'] = '{{ru}}'
tmpl['afmt'] = '{{FrontSide}}\n\n<hr id=answer>\n\n<div class="from">{{en}}</div>'
collection.models.addTemplate(model, tmpl)

model['id'] = 12345678  # essential for upgrade detection
collection.models.update(model)
collection.models.setCurrent(model)
collection.models.save(model)

note = anki.notes.Note(collection, model)
note['en'] = "hello"
note['ru'] = u"[heləʊ]\nint. привет"
note.guid = "xxx1"
collection.addNote(note)

note = collection.newNote()
note['en'] = "bye"
note['ru'] = u"[baɪ]\nint. пока"
note.guid = "xxx2"
collection.addNote(note)

export = AnkiPackageExporter(collection)
export.exportInto(FONAME)

As long you keep note.guid and model['id'] the same, you can import the DB and update cards without losing progress!

  • Any way to build apkg from command line without GUI?
  • Is it possible to merge improvements and corrections to cards during apkg import without loosing progress?

examples of my production code:

  • http://hg.defun.work/gadict/file/tip/py/gadict_srs_anki.py or copy
  • http://hg.defun.work/gadict/file/tip/obsolete/exp_anki.py or copy

Tags:

Csv

Export

Anki