I'm trying to write a simple code that is capable of reading a PGN file and searching for moves and comments throughout the variant tree. However, I have not been successful, I have not yet been able to understand how I access the moves for a particular variant outside the main line.

Here is an example.

Reading the game from the pgn file below:

[Event "?"]
[Site "?"]
[Date "????.??.??"]
[Round "?"]
[White "Study"]
[Black "Variant Caro-Kann"]
[Result "1/2-1/2"]
[ECO "B12"]
[Annotator "Joao Paulo"]
[PlyCount "10"]
[EventDate "2020.03.04"]
[SourceDate "2020.03.04"]

  1. e4 c6 2. d4 d5 3. e5 {Variant 1} (3. exd5 {Variant 2} cxd5 4. Nf3 Nd7 (4... Nf6 {Variant 2.2} 5. c4 dxc4 6. Bxc4 e6) 5. Nc3 Ngf6) (3. Nc3 {Variant 3} dxe4 4. Nxe4 Nd7 5. Nf3 Ngf6) (3. Nd2 {Variant 4} dxe4 4. Nxe4 Nf6 5. Nxf6+ gxf6) 3... Bf5 4. Bd3 Bxd3 5. Qxd3 e6 1/2-1/2

Using the following code:

import chess
import chess.pgn
pgn = open("pgns/Variants Caro-Kann.pgn")
game = chess.pgn.read_game(pgn)
bd = game.board()
node = game
ct = 0;
while not node.is_end():
    print('Current Move')
    node = node.variations[0]
    if node.is_end() == 0:
        print('Next Move')
How could I access the bids for the entire variant tree (variants: 2, 2.2, 3 and 4)?
I would appreciate your help.

1 Answer 1


If you want to access every node, then you're basically iterating over the game tree. A straightforward recursion will get you there, something like:

def traverse(node):
    # do whatever stuff you want for the node here
    # terminating condition
    if (node.is_end()):
    # recursion
    for child_node in node.variations:

And to use it, call traverse(game) where game is the root node of your game.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.