如何在Python中将数据保存到文本文件

7
我可以帮助您翻译以下IT技术相关内容。这里是制作一个简单的随机数字游戏,我希望能够在程序关闭并再次运行后保存玩家的最高分数。我希望计算机可以询问玩家的姓名,搜索文本文件中的姓名数据库,并显示他们的最高分数。如果他们的姓名不在其中,则创建一个新的数据库名称。我不确定如何做到这一点。我是一个初学者程序员,这是我的第二个程序。感激任何帮助。
下面是随机数字游戏的代码:
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)

编辑: 我正在尝试这样做,并且它似乎在工作,但是,当我尝试使用变量替换字符串时,它会报错:

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()

Pickle可以将变量存储/检索到文件中。JSON也可以实现此功能。 - jkd
你如何准确地使用“pickle”? - vkumar
请查看文档 - TigerhawkT3
1
导入pickle库,然后使用f = open('文件名', 'w')打开一个文件。创建一个对象来存储所有需要存储的数据,并使用pickle.dump(obj, f)将其存储在文件中。请不要将单词“file”或“object”用作Python变量名称。来源:http://python.about.com/od/pythonstandardlibrary/a/pickle_intro.htm - jkd
在我看来,JSON更加用户友好。 - jkd
3个回答

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

使用 with 像这样的方式是处理文件的首选方式,因为它可以自动处理文件关闭,即使出现异常。

另外,请记住修复您的 getscore() 方法,以便它不总是返回0。如果您希望它也打印分数,请在 return 之前放置 print 语句。


9
为了使用Python编写文件,请按照以下步骤操作:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()

如果您想读取或附加文件,请将 'w' 更改为 'r' 或 'a'


2

首先,您应该清楚地提出问题,以便其他人能够理解。要将文本添加到文本文件中,您可以始终使用open内置函数。操作如下。

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

这就是全部内容。如果需要进一步帮助,请尝试访问这个网站:http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/ 你也可以使用for循环来打印游戏中的所有得分。自己尝试一下,会很有趣。 推荐的方法 好吧,如果要使用推荐的方式,就像这样使用它:
>>> with open('test.txt', 'w') as a:
        a.write('theunixdisaster\t 05')

这样做可以确保文件关闭。

使用变量

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

现在尝试调用它。我使用的是python 3.4.2。因此,如果出现错误,请检查您使用的python版本中的字符串格式是否有任何差异。


我能用一个变量名替换'theunixdisaster'吗? - vkumar
可以的。首先写出我的代码的第一行。然后将变量b设置为theunixdisaster。接着继续写出我的代码的其他行。别忘了用变量b替换第二行中的theunixdisaster - user4696550
我没有使用 "the",对吧? - user4696550
@theunixdisaster 当我尝试替换“theunixdisaster”时,它不起作用。我将编辑主帖并提供代码。 - vkumar
@user3184082,尝试使用字符串格式化。我会在我的答案中展示它。 - user4696550
显示剩余9条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接