如何用Python创建空Anki卡组?Anki插件开发技术求助
Absolutely! When building an Anki add-on, creating an empty deck programmatically is straightforward once you leverage Anki's internal Python API. Here's a step-by-step breakdown with code examples tailored to your use case:
Core Concepts
Anki's main window object (mw) gives you access to the collection of decks, notes, and cards. The mw.col.decks manager handles all deck-related operations—this is what we'll use to create our empty deck.
Step 1: Create the Empty Deck
First, write a function to create a deck (and handle cases where the deck name already exists to avoid errors):
def create_empty_deck(deck_name): # Check if the deck already exists deck_id = mw.col.decks.id(deck_name) if deck_id: # Optional: Return existing deck ID or handle as needed print(f"Deck '{deck_name}' already exists!") return deck_id # Create a new empty deck deck_id = mw.col.decks.add(deck_name) # Save changes to the collection (critical to persist the deck) mw.col.save() print(f"Created empty deck '{deck_name}' with ID: {deck_id}") return deck_id
Key Notes:
mw.col.decks.id(deck_name)checks for an existing deck by name and returns its ID if found.mw.col.decks.add(deck_name)creates a new deck and returns its unique ID.- Always call
mw.col.save()after modifying the collection—this ensures your changes are written to disk and persist across Anki sessions.
Step 2: Import Text Content into the Deck
Once you have your empty deck, you can parse your text file and add notes to it. Here's a simplified example of adding basic notes (adjust the note type and fields to match your text file's structure):
def import_text_to_deck(deck_id, text_file_path): # Get the default "Basic" note type (replace with your custom type if needed) note_type = mw.col.models.by_name("Basic") # Set the target deck and note type as active mw.col.decks.select(deck_id) mw.col.models.set_current(note_type) # Parse your text file (example: each line uses tab to separate front/back content) with open(text_file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue # Split line into front and back fields (adjust delimiter to match your file) front, back = line.split('\t', 1) # Create a new note and populate its fields note = mw.col.new_note() note.fields[0] = front # First field of the note type (Front) note.fields[1] = back # Second field of the note type (Back) # Add the note to the target deck mw.col.add_note(note, deck_id) # Save all imported changes mw.col.save() print(f"Successfully imported content to deck ID {deck_id}")
Putting It All Together
Call these functions in your add-on to create the deck and import your text content:
# Example usage target_deck_name = "My Custom Import Deck" text_file_path = "/path/to/your/text/content.txt" # Create the empty deck deck_id = create_empty_deck(target_deck_name) # Import text content into the deck import_text_to_deck(deck_id, text_file_path)
Important Considerations
- Anki Version Compatibility: This code works for Anki 2.1+. For very old versions, some API methods may differ (e.g.,
decks.new_deck()instead ofdecks.add()). - Error Handling: Add try/except blocks to handle file reading errors, invalid deck names, or duplicate notes based on your add-on's needs.
- Custom Note Types: If you're using a non-default note type, replace
"Basic"with your note type's name and adjust thefieldsindices to match its structure.
内容的提问来源于stack exchange,提问作者lua




