简体   繁体   中英

How do I save data in a text file 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()

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM