0

I'm new to working with python-chess and I was perusing the official documentation. I noticed this very weird thing I just can't make sense of. This is from the documentation:

import chess.pgn

pgn = open("data/pgn/kasparov-deep-blue-1997.pgn")

first_game = chess.pgn.read_game(pgn)
second_game = chess.pgn.read_game(pgn)

So as you can see the exact same function pgn.read_game() results in two different games to show up. I tried with my own pgn file and sure enough first_game == second_game resulted in False. I also tried third_game = chess.pgn.read_game() and sure enough that gave me the (presumably) third game from the pgn file. How is this possible? If I'm using the same function shouldn't it return the same result every time for the same file? Why should the variable name matter(I'm assuming it does) unless programming languages changed overnight or there's a random function built-in somewhere?

Abhishek
  • 553
  • 2
  • 9
  • 26

1 Answers1

1

The only way that this can be possible is if some data is changing. This could be data that chess.pgn.read_game reads from elsewhere, or could be something to do with the object you're passing in.

In Python, file-like objects store where they are in the file. If they didn't, then this code:

with open("/home/wizzwizz4/Documents/TOPSECRET/diary.txt") as f:
    line = f.readline()
    while line:
        print(line, end="")
        line = f.readline()

would just print the first line over and over again. When data's read from a file, Python won't give you that data again unless you specifically ask for it.

There are multiple games in this file, stored one after each other. You're passing in the same file each time, but you're not resetting the read cursor to the beginning of the file (f.seek(0)) or closing and reopening the file, so it's going to read the next data available – i.e., the next game.

wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
  • I think I understand. So it's a different methodology for files in Python? Is there any function to iterate over all the games in the PNG file? I want to get a move-by-move information from all of the 1197 games in there – Abhishek May 05 '19 at 03:08