pythonanki

how to programmatically import text file into anki?


I'm trying to make an Addon that converts text from a website into an Anki deck, so now I have a text file that is formatted correctly and I can't figure out how to import it into an existing deck, I checked the official manual but it offers very little explanation, this may be sounding very newbie but this is my first time working on an Addon, so if someone with more experience can give me more thorough explanation, thanks in advance!

This is the code snippet from the website that I'm trying to understand:

from anki.importing import TextImporter
file = u"/path/to/text.txt"
# select deck
did = mw.col.decks.id("ImportDeck")
mw.col.decks.select(did)
# anki defaults to the last note type used in the selected deck
m = mw.col.models.byName("Basic")
deck = mw.col.decks.get(did)
deck['mid'] = m['id']
mw.col.decks.save(deck)
# and puts cards in the last deck used by the note type
m['did'] = did
# import into the collection
ti = TextImporter(mw.col, file)
ti.initMapping()
ti.run()

Solution

  • I take it that you're trying to make an Anki 2.0 add-on. I would strongly recommend that you make an Anki 2.1 add-on instead, since it is cleaner, has more development features and uses Python 3.

    That aside, here's an explanation of the code: