0

So I'm currently using 'shelve' to save game data for a game I'm working on, however when I use pyinstaller to pack this game into an exe it creates 3 different file's all with the same name but different file types, even though when creating the file I don't specify a file type.

def save_game(yn):
    if yn:
        file = shelve.open('savegame', 'n')
        file['map'] = map
        file['objects'] = objects
        file['player_index'] = objects.index(player)  # index of player in objects list
        file['stairs_index'] = objects.index(stairs)  # same for the stairs
        file['inventory'] = inventory
        file['game_msgs'] = game_msgs
        file['game_state'] = game_state
        file['dungeon_level'] = dungeon_level
        file.close()

this creates the save file with no file type (which works great!) however in exe form it creates 'savegame.bak', 'savegame.dir', and 'savegame.dat' when the player dies I call a function which saves the file (in case there is no save file) and then delete it, so you can't access your ended game save.

def player_death(player):
    # the game ended!
    global game_state

    ...

    game_state = 'dead'

    ...

    save_game(True)
    os.remove('savegame')

In short I just need to know how I can make the os.remove line get rid of the savegame whether it's just 1 file or 3 different files all with different file types.

floomp
  • 1

2 Answers2

0

one option is to use pathlib.

from pathlib import Path

for file in Path("/path/to/dir/with/saves").glob('savegame.*') :
    file.unlink()
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
0

if you can express it with wildcards, the glob module is for you.

from glob import iglob

for file in iglob("savegame.*"):
    os.remove(file)

note: if you know that you will only match a few files, you can safely use glob instead of iglob. if you don't know how many files you will match, you should generally use iglob to not end up with a huge list in memory.

MCO
  • 1,187
  • 1
  • 11
  • 20