8

So I am making a simple randomized number game, and I want to save the players High Score even after the program is shut down and ran again. I want the computer to be able to ask the player their name, search through the database of names in a text file, and pull up their high score. Then if their name is not there, create a name in the database. I am unsure on how to do that. I am a noob programmer and this is my second program. Any help would be appreciated.

Here is the Code for the random number game:

import random
import time

def getscore():
    score = 0
    return score
    print(score)


def main(score):
    number = random.randrange(1,5+1)
    print("Your score is %s") %(score)
    print("Please enter a number between 1 and 5")

    user_number = int(raw_input(""))

    if user_number == number:
        print("Congrats!")
        time.sleep(1)
        print("Your number was %d, the computers number was also %d!") %(user_number,number)
        score = score + 10
        main(score)

    elif user_number != number:
        print("Sorry")
        time.sleep(1)
        print("Your number was %d, but the computers was %d.") %(user_number, number)
        time.sleep(2)
        print("Your total score was %d") %(score)
        time.sleep(2)
        getscore()

score = getscore()
main(score)
main(score)

EDIT: I am trying this and it seems to be working, except, when I try to replace the string with a variable, it gives an error:

def writehs():
    name = raw_input("Please enter your name")
    a = open('scores.txt', 'w')
    a.write(name: 05)
    a.close()

def readhs():
    f = open("test.txt", "r")
writehs()
readhs()
5
  • Pickle can store/retreive variables in a file. JSON can also do this. Commented Mar 24, 2015 at 1:28
  • how exactly do you use 'pickle' Commented Mar 24, 2015 at 1:29
  • See the documentation. Commented Mar 24, 2015 at 1:32
  • 1
    import pickle then f = open('filename', 'w'), then create an object with all the data you want to store, then use pickle.dump(obj, f). Never use the words file or object as a python variable name. From: python.about.com/od/pythonstandardlibrary/a/pickle_intro.htm Commented Mar 24, 2015 at 1:33
  • JSON is much more user friendly in my opinion. Commented Mar 24, 2015 at 1:54

3 Answers 3

15
with open('out.txt', 'w') as output:
    output.write(getscore())

Using with like this is the preferred way to work with files because it automatically handles file closure, even through exceptions.

Also, remember to fix your getscore() method so it doesn't always return 0. If you want it to print the score as well, put the print statement before the return.

Sign up to request clarification or add additional context in comments.

Comments

9

In order to write a file using python do the following:

file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()

If you want to read or append the file just change 'w' for 'r' or 'a' respectively

Comments

3

First of all you should ask your question clearly enough for others to understand.To add a text into text file you could always use the open built-in function.Do it like this.

>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()

Thats all.If need further help try this website. http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/

You could also use a for loop for the game to print all the scores. Try this one on your own.It would rather be fun.

THE RECOMENDED WAY

Well as if the recommended way use it like this:

>>> with open('test.txt', 'w') as a:
        a.write('theunixdisaster\t 05')

With this its certain that the file would close.

With variables

>>> name = sempron
>>> with open('test.txt', 'w') as a:
        a.write('%s: 05' % name)

Now try calling it.Well I use python 3.4.2.So, if you get into errors, try to check if there is any difference in the string formatting with the python version that you use.

14 Comments

Ok, sorry my question was not clear enough, Ill try the for loop. Thanks for your help
Can i replace the 'theunixdisaster' with a variable name?
If you could wait a minute I would search the web give a proper answer to that.
Yes you could.First write the first line of my code.Then set a variable b to theunixdisaster.Then carry the other lines in my code.Don't forget to replace the 'theunixdisaster' in line two with the variable b.
Thank You So Much you have been really helpful!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.