-1

I would like to have a check for save games for a command-line game I'm working on.

The save games are singular ".txt" files, and the way this short piece of code works is it tries to open the "name.txt" file in the "%appdata%\Roaming\AdventureChapt1\" folder, then looks for an error message when Python can't find the file.

How would I do this?

print('Loading Save Data')

savecheck = open('%appdata%/Roaming/AdventureChapt1/name.txt', 'rt')

if savecheck.read() == '':
    newgame() # calls the "newgame" function to bring up the New Game wizard
whoisraibolt
  • 2,082
  • 3
  • 22
  • 45
ByeMC
  • 15
  • 3

2 Answers2

2

You can use try and except

try:
    with open('%appdata%/Roaming/AdventureChapt1/name.txt', 'rt') as savecheck:
        # code that reads saved game
except FileNotFoundError:
    newgame()
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can use a variety of things to see if the file exists or not.
My flavour is

from os import path
filepath = "path_to_file"
if not path.exists(filepath):
    # do stuff when file doesn't exist

ref: https://www.guru99.com/python-check-if-file-exists.html

shark
  • 467
  • 3
  • 13