带有文本文件的 Python 高分 [英] Python Highscores w/ text file

查看:17
本文介绍了带有文本文件的 Python 高分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个基于文本的游戏,并且在尝试制作我的最后一个函数 highscore 时遇到了问题.我的问题是这样的,我想让函数保存我的前五个 scores 并将其保存到一个文本文件中,以及玩家的 username,然后就可以将此打印到我的基于文本的游戏中.我知道这可能很难做到,但我希望将分数保存在文本文件中,而不是像我所看到的那样保存在 pickle 中,因为我想与一些朋友.任何帮助表示赞赏,谢谢,汤姆.

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.

我很乐意打开文件进行写作.我的代码包含 scores.sort 命令,但我不确定如何将 5 个分数放入文件中,并删除第 6 个分数.谢谢你的帮助,汤姆

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

推荐答案

欢迎使用 Stack Overflow!你用什么在 Python 中存储你的高分?一堂课,一本字典?

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}\n'.format(username, score))

这篇关于带有文本文件的 Python 高分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆