Skip to content

Instantly share code, notes, and snippets.

@glennhefley
Last active June 27, 2024 18:43
Show Gist options
  • Select an option

  • Save glennhefley/59cdc439d5f66f4e9e2b1120faaedd24 to your computer and use it in GitHub Desktop.

Select an option

Save glennhefley/59cdc439d5f66f4e9e2b1120faaedd24 to your computer and use it in GitHub Desktop.
Here's a Python script that provides the functionality to discover PGN files in the current directory, list them, combine them into a single PGN file, delete the original files, and exit the program based on user prompts:
'''
Here's a Python script that provides the functionality to discover PGN files in the current directory, list them, combine them into a single PGN file, delete the original files, and exit the program based on user prompts:
Explanation:
discover_pgn_files(): This function lists all files in the current directory that have the .pgn extension.
list_pgn_files(pgn_files): This function prints the list of discovered PGN files.
combine_pgn_files(pgn_files, output_file='combined.pgn'): This function combines all the discovered PGN files into a single output file named combined.pgn by default.
delete_pgn_files(pgn_files): This function deletes the PGN files listed in the pgn_files list.
main(): The main function that provides a menu for the user to choose options: combine PGN files, delete original PGN files, or exit the program.
Usage:
Save the script to a file, for example, pgn_manager.py.
Run the script using Python:
python pgn_manager.py
Follow the on-screen prompts to list, combine, delete, or exit the program.
'''
import os
import chess.pgn
def discover_pgn_files():
pgn_files = [f for f in os.listdir() if f.endswith('.pgn')]
return pgn_files
def list_pgn_files(pgn_files):
if not pgn_files:
print("No PGN files found in the current directory.")
else:
print("PGN files in the current directory:")
for i, file in enumerate(pgn_files):
print(f"{i + 1}. {file}")
def combine_pgn_files(pgn_files, output_file='combined.pgn'):
with open(output_file, 'w') as outfile:
for fname in pgn_files:
with open(fname) as infile:
outfile.write(infile.read())
outfile.write('\n\n')
print(f"Combined PGN files into {output_file}")
def delete_pgn_files(pgn_files):
for file in pgn_files:
os.remove(file)
print("Deleted the original PGN files.")
def main():
while True:
pgn_files = discover_pgn_files()
list_pgn_files(pgn_files)
print("\nOptions:")
print("1. Combine all PGN files into one")
print("2. Delete the original PGN files")
print("3. Exit")
choice = input("Enter your choice: ").strip()
if choice == '1':
if pgn_files:
combine_pgn_files(pgn_files)
else:
print("No PGN files to combine.")
elif choice == '2':
if pgn_files:
delete_pgn_files(pgn_files)
else:
print("No PGN files to delete.")
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
if __name__ == "__main__":
main()
'''
Explanation:
discover_pgn_files(): This function lists all files in the current directory that have the .pgn extension.
list_pgn_files(pgn_files): This function prints the list of discovered PGN files.
combine_pgn_files(pgn_files, output_file='combined.pgn'): This function combines all the discovered PGN files into a single output file named combined.pgn by default.
delete_pgn_files(pgn_files): This function deletes the PGN files listed in the pgn_files list.
main(): The main function that provides a menu for the user to choose options: combine PGN files, delete original PGN files, or exit the program.
Usage:
save as pgndb.py.
Run the script using Python:
python pgndb.py
Follow the on-screen prompts to list, combine, delete, or exit the program.
'''
import os
import chess.pgn
def discover_pgn_files():
pgn_files = [f for f in os.listdir() if f.endswith('.pgn')]
return pgn_files
def list_pgn_files(pgn_files):
if not pgn_files:
print("No PGN files found in the current directory.")
else:
print("PGN files in the current directory:")
for i, file in enumerate(pgn_files):
print(f"{i + 1}. {file}")
def combine_pgn_files(pgn_files, output_file='combined.pgn'):
with open(output_file, 'w') as outfile:
for fname in pgn_files:
with open(fname) as infile:
outfile.write(infile.read())
outfile.write('\n\n')
print(f"Combined PGN files into {output_file}")
def delete_pgn_files(pgn_files):
for file in pgn_files:
os.remove(file)
print("Deleted the original PGN files.")
def main():
while True:
pgn_files = discover_pgn_files()
list_pgn_files(pgn_files)
print("\nOptions:")
print("1. Combine all PGN files into one")
print("2. Delete the original PGN files")
print("3. Exit")
choice = input("Enter your choice: ").strip()
if choice == '1':
if pgn_files:
combine_pgn_files(pgn_files)
else:
print("No PGN files to combine.")
elif choice == '2':
if pgn_files:
delete_pgn_files(pgn_files)
else:
print("No PGN files to delete.")
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
if __name__ == "__main__":
main()
@glennhefley
Copy link
Author

Here's a Python script to achieve the tasks you've mentioned: opening a PGN file, discovering if it holds one or many games, listing the games by number, displaying a game, and exiting. For displaying the game using Notepad++, the script will write the game to a temporary file and open it with Notepad++.

First, you need to install the chess library to handle PGN files. You can install it using pip:

pip install python-chess

Now, here's the Python script:

import chess.pgn
import os
import tempfile
import subprocess

def open_pgn(file_path):
    games = []
    with open(file_path, 'r') as pgn_file:
        while True:
            game = chess.pgn.read_game(pgn_file)
            if game is None:
                break
            games.append(game)
    return games

def list_games(games):
    for i, game in enumerate(games):
        print(f"Game {i+1}: {game.headers.get('Event', 'Unknown Event')} - {game.headers.get('White', 'Unknown')} vs {game.headers.get('Black', 'Unknown')}")

def display_game(game):
    with tempfile.NamedTemporaryFile(delete=False, suffix=".pgn") as temp_file:
        temp_file.write(str(game).encode())
        temp_file_path = temp_file.name
    
    subprocess.run(["notepad++", temp_file_path])

def main():
    file_path = input("Enter the path to the PGN file: ")
    if not os.path.isfile(file_path):
        print("File not found!")
        return
    
    games = open_pgn(file_path)
    
    if len(games) == 0:
        print("No games found in the file.")
        return
    
    if len(games) == 1:
        print("Single game found in the file.")
        display_game(games[0])
    else:
        print(f"{len(games)} games found in the file.")
        list_games(games)
        while True:
            try:
                choice = int(input("Enter the game number to display or 0 to exit: "))
                if choice == 0:
                    break
                elif 1 <= choice <= len(games):
                    display_game(games[choice - 1])
                else:
                    print("Invalid choice. Please enter a number between 1 and", len(games))
            except ValueError:
                print("Invalid input. Please enter a number.")

if __name__ == "__main__":
    main()

Explanation:

  1. open_pgn(file_path): This function reads the PGN file and returns a list of games.
  2. list_games(games): This function lists the games found in the PGN file, displaying the game number and basic details like the event name and player names.
  3. display_game(game): This function writes the selected game to a temporary PGN file and opens it with Notepad++.
  4. main(): This is the main function that coordinates the process. It prompts the user for the file path, opens the PGN file, checks the number of games, lists the games if there are multiple, and allows the user to select a game to display or exit.

Usage:

  1. Save the script to a file, for example, chess_pgn_viewer.py.
  2. Run the script using Python:
    python chess_pgn_viewer.py
  3. Follow the on-screen prompts to enter the path to the PGN file, list games, and display a selected game in Notepad++.

Make sure Notepad++ is installed and accessible from the command line for the subprocess.run to work correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment