0

I created a game successfully except I cannot save scores.

I have been trying to save the variable that I use for points to a text file, and have managed that, but would like a way to read it from it when the program launches.

My code for saving it is below.

def Save():
    f.open("DO NOT DELETE!", "w+")
    f.write(str(points))
    f.close()
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    What's the problem here? You seem to know how to `open` and `write`. Try reading the documentation on `read` method – OneCricketeer May 24 '17 at 01:18
  • 1
    Tip for beginners: look into [pickle](https://docs.python.org/3/library/pickle.html) – Taku May 24 '17 at 01:19
  • the main problem is that I need to read the file and then set it to a variable. I am struggling with this because if the file does not exist, it is trying to read from a non-existant file. I have tried if statements and everything, but can't get it to work. – Jason Stuther May 24 '17 at 01:23

1 Answers1

0

I would recommend you to use the pickle library. Further reading: Python serialization - Why pickle (Benefits of pickle). As for your question,

I am struggling because if the file does not exist, it is trying to read from a non-existant file.

You can use a try...except... clause to catch FileNotFoundError

import pickle as pkl

# to read the highscore:
try:
    with open('saved_scores.pkl', 'rb') as fp:
        highscore = pkl.load(fp) # load the pickle file
except (FileNotFoundError, EOFError): # error catch for if the file is not found or empty
    highscore = 0

# you can view your highscore
    print(highscore, type(highscore)) # thanks to pickle serialization, the type is <int>

# you can modify the highscore
highscore = 10000 # :)

# to save the highscore:
with open('saved_scores.pkl', 'wb') as fp:
    pkl.dump(highscore, fp) # write the pickle file
Taku
  • 31,927
  • 11
  • 74
  • 85
  • thanks for this. It isn't quite what I am looking for, but works, and I will keep this in mind if another situation arises. Very useful! :) – Jason Stuther May 24 '17 at 07:04