Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

Python Highscores w/ text file

i am currently working on a text based game, and have run into a problem trying to make my last function, highscore. My problem is this, i would like to make the function save my top five scores and save it to a text file, along with the player's username, and then be able to print this into my text based game. I know this could be hard to do, but i would like it if the scores were saved in a text file, and not a pickle as i have seen suggested, as i would like to share the file with some friends. Any help is appreciated, Thanks, Tom.

edit: I am comfortable opening the file for writing. my code included the scores.sort command, but i wasn't sure how to put 5 scores into the file, and have the 6th score deleted. Thanks for the help, Tom

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Welcome to Stack Overflow! What are you using to store your high scores in Python? A class, a dictionary?

To simply write string content to a file you can do the following:

scores = [('username1', 123), ('username2', 456)]
with open('scores.txt', 'w') as f:
    for username, score in scores:
        f.write('Username: {0}, Score: {1}
'.format(username, score))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...