Anki Python Module update_note not writing as expected

I have an imported Anki deck for learning Chinese, but some odd proportion of the notes are using traditional rather than simplified characters. I wrote a script using OpenCC and the Anki module to automatically go in and convert the “Mandarin” field on all my notes to use simplified characters, but I’m finding that the collections.update_note method is not behaving as expected. I update a note to include the new simplified characters instead of the old traditional ones, but upon opening Anki or querying for the note with the python module, I find the note has not changed at all. I don’t get any error messages upon updating the note, though.

In order to reproduce the issue, please create a note with the following fields:

Mandarin : 歷史
Pinyin : lìshǐ

and run the following two scripts in succession (note that if you have any other decks with traditional Chinese, running this script may alter one of your notes in an undesirable way).

import sys
from anki.collection import Collection

COLLECTION_PATH = sys.argv[1]
col = Collection(COLLECTION_PATH)
note = col.get_note(col.find_notes("lìshǐ")[0])
assert note["Mandarin"] != "历史"
note["Mandarin"] = "历史"
col.update_note(note)
import sys
from anki.collection import Collection

COLLECTION_PATH = sys.argv[1]
col = Collection(COLLECTION_PATH)
note = col.get_note(col.find_notes("lìshǐ")[0])
assert note["Mandarin"] != "历史"

If both scripts run successfully, I believe that should suffice to show that the note was not updated as expected.

My problem was solved by col.save(trx=False) at the end of my script. I’m pleased that I found a solution, but I wish this was highlighted in the doc examples. The fact that it’s not makes me think that maybe this wasn’t supposed to be necessary, and the fact that I needed it is itself a bug.

It was already shown in the example, but I’ll add a line pointing out why it should be called.

https://addon-docs.ankiweb.net/command-line-use.html

1 Like

You’re very right, my bad for not noticing this. Thanks so much for pointing it out!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.