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
1 回答
我建议你使用pickle库 . 进一步阅读:Python serialization - Why pickle (Benefits of pickle) . 至于你的问题,
您可以使用
try...except...
子句来捕获FileNotFoundError