Importing CSV with file headers with anki.importing

I have tried to import csv files with file headers with the code below, but it completely disregarded the file headers I put at the beginning of the file.

ti = TextImporter(mw.col, "myfile.csv")
ti.initMapping()
ti.run()

There is a section in the Add-on documentation about importing (see below), but it specifies the Deck and the the Notetype before import, I would like to specify it in the second column.

I am able to do it manually, I just need to hit Import after selecting the file for it to import correctly.

my file headers:

#html:true					
#notetype column:2					
#deck column:3					
#tags column:6					
#guid column:1					
#separator:Tab					
#columns:GUID	Notetype	Deck	Front	Back	tags

You’re calling the old importer which doesn’t understand headers. The new importer is callable with Collection.import_csv().

Oh, and you probably need get_csv_metadata() as well, to read in headers beforehand.

What should I write to Collection.import_csv(), because I don’t know what the request parameter of type ImportCsvRequest is?

I’ve updated the example in the docs.

3 Likes

The finished code can be found here under the Import a text file into the collection

from anki.collection import ImportCsvRequest
from aqt import mw
col = mw.col
path = "/home/dae/foo.csv"
metadata = col.get_csv_metadata(path=path, delimiter=None)
request = ImportCsvRequest(path=path, metadata=metadata)
response = col.import_csv(request)
print(response.log.found_notes, list(response.log.updated), list(response.log.new))

Thanks for your help Rumo and dae.

1 Like