-5
score=(uName, '=', uCoins)
try:
    with open('saveScore.txt', 'rb') as file:
        score=pickle.load(file)
except:
    score==0
with open('saveScore.txt', 'wb') as file:
    pickle.dump(score, file)

This is my code, I need help saving the score for each particular execution of the program without overwitting any previous saved scores. I cannot seem to get it to work.

Richard
  • 6,812
  • 5
  • 45
  • 60
  • What is `score==0` supposed to be doing? Where (if anywhere) are you adding to `scope` before dumping it back out? Do you have any more information than *"I cannot seem to get it to work"*? – jonrsharpe Jun 03 '15 at 12:47
  • 1
    Then [RTFM](https://docs.python.org/2/tutorial/datastructures.html#dictionaries)! – jonrsharpe Jun 03 '15 at 12:48
  • I am not sure, I have found that code elsewhere and edited it to suit my needs – Anthony Hanrahan Jun 03 '15 at 12:49
  • Basically, I want to save the score from the execution of the game, without overwriting any previous scores. – Anthony Hanrahan Jun 03 '15 at 12:50
  • So you need a *container* to hold the tuples of scores (e.g. a `list` or `dict`) then you can `pickle` that rather than the single tuple you're currently using. Or use JSON, as you've also been suggested to do. – jonrsharpe Jun 03 '15 at 12:51
  • Do you just want to append to the file, rather than opening it, reading it, then writing it all back out again? http://stackoverflow.com/questions/4706499/ – kponz Jun 03 '15 at 12:51
  • A flat text file (or CSV) might be better suited than a pickle. If you wish to keep all previous scores, why not just append the score to a text file? – mhawke Jun 03 '15 at 12:52
  • @kponz appending to the file is a bad idea when using `pickle` – jonrsharpe Jun 03 '15 at 12:53
  • I understand that @kponz, but can you please tell me, what does the 'write refer to? – Anthony Hanrahan Jun 03 '15 at 12:54
  • 2
    Frankly, if you don't know what writing to a file means, you have bigger problems than we can really help you with. I would strongly suggest you consider finding and following a structured introductory programming tutorial. See e.g. https://wiki.python.org/moin/BeginnersGuide/NonProgrammers – jonrsharpe Jun 03 '15 at 12:56

1 Answers1

1

To write to a file without overwriting it, you open the file in 'append' mode with the 'a' flag to open. In the below code snippet, I'm using random simply for example purposes:

#!/usr/bin/python

import random

score = random.randint(1, 500)

wfh = open('score.txt', 'a')

print(str(score))

wfh.write("{}\n".format(score))

wfh.close

Here I run it multiple times, then after that I print out the contents of the file which have retained all my 'scores':

$ ./score.py
159
$ ./score.py
156
$ ./score.py
224
$ ./score.py
235

$ cat score.txt 
159
156
224
235
stevieb
  • 9,065
  • 3
  • 26
  • 36