How to isolate a single game from a pgn file containing multiple games in python?

523 Views Asked by At

I have a pgn file with multiple games. I want to separate all the games into different files or just one text file so that I can separate all the White moves and Black moves. Any help?

1

There are 1 best solutions below

2
On

Assuming your file looks like this:

[Event "Llyods Bank"] [...]

1.e4 [...]

[Event "Lloyds Bank"] [...]

1.e4 [...]

Then, a simple approach would be to append to the list all the lines until you find the 2nd '\n'

Here's a naive piece of code:

from os import read


my_file = open("Adams.pgn", "r")
content_list = my_file. readlines()
print(content_list)

list_games = []
game = []
j = 0
for i in content_list:
    if i == "\n":
        j += 1
    if j == 2:
        j = 0
        list_games.append(game)
        game = []
    game.append(i)
if game.empty() == False:
    list_games.append(game)

for i in game:
    print(game)