Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save data in a text file python

Tags:

python

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()
like image 701
vkumar Avatar asked Nov 30 '22 18:11

vkumar


1 Answers

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.

like image 117
TigerhawkT3 Avatar answered Dec 05 '22 12:12

TigerhawkT3