Extracting move information from a pgn file on Python

Viewed 5666

How do I go about extracting move information from a pgn file on Python? I'm new to programming and any help would be appreciated.

4 Answers

Try pgnparser.

Example code:

import pgn
import sys

f = open(sys.argv[1])
pgn_text = f.read()
f.close()
games = pgn.loads(pgn_text)
for game in games:
    print game.moves

@Dennis Golomazov I like what Denis did above. To add on to what he did, if you want to extract move information from more than 1 game in a png file, say like in games in chess database png file, use chess.pgn.

import chess.pgn 
png_folder = open('sample.pgn')
current_game = chess.pgn.read_game(png_folder)
png_text = str(current_game.mainline_moves())

read_game() method acts as an iterator so calling it again will grab the next game in the pgn.

Related