Pack CSV and images in an .apkg?


I’m writing a script (in Python) to programmatically generate anki notes. The notes should contain images (which the script also generates), and I’m currently doing this as follows:

  • Associating each card with some UUID, and putting that as a field in the note
  • Generating the images and naming them “UUID”.svg
  • Copy the images I get from the script into the folder
  • Importing the CSV with the notes
  • The card template I use with the notes then embeds the SVG with the correct filename, and this all works fine

I want to package the notes with the images in one file to cut out one of the last two steps, and I think an .apkg file is what I want. Can someone advise on how to go about doing this programatically (or point me in the right direction if there are some functions in the Python anki library that do this, I had a look but couldn’t really find what I was looking for).


I’m afraid Anki does not currently provide a way to bundle media with text imports.

Please also see Field Replacements - Anki Manual

So I suppose the only option to bundle into an apkg is to reverse engineer the file format?

And thanks for the link about media best practice - so am I right in saying that “[img src=UUID.svg>” should be in the field of my note (rather than just the UUID and then the note template including the image tag)?

No, you can (and should) use Anki’s API: Command-Line Use - Writing Anki Add-ons


Apologies, I’m a little confused (maybe I’ve not communicated the issue well).

I understand that I can use the anki python library to import a text file. Once I’ve done so, can I then export that deck, with media included, into an apkg file? If not, how does the anki application do it? If so, where should I be looking?

Basically: I have a text file containing notes, and a bunch of images. I want to use the anki library to “import them” into a collection object, and then “export them” as an apkg, with the idea that I then I have one file that I can send to friends, import into the desktop app, etc.

Thanks for your help!

1 Like

Something like this?

deck_name =
exporter = AnkiPackageExporter(mw.col)
exporter.did = did
exporter.includeMedia = True
exporter.includeTags = True
# Change to wherever you want to save the .apkg.
out_dir = pathlib.Path(tempfile.mkdtemp())
out_file = out_dir / f"{deck_name}.apkg"

The code I linked was introduced in 2.1.52. The code you’ve included targets the old exporter, which will be removed at one point.

1 Like

I stopped working on this after I posted this but I’m back on it again. I understand how exporting works now, but I’m sill having some difficulty in using the API to make a collection object and import my text file of notes.

In particular, how can I make a new NoteType in a collection? I don’t want to use aqt, just pylib/anki.