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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29223246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:14:21  来源:igfitidea点击:

How do I save data in a text file python

python

提问by vkumar

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

回答by dgsleeps

In order to write a file using python do the following:

要使用 python 编写文件,请执行以下操作:

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

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

回答by TigerhawkT3

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

Using withlike this is the preferred way to work with files because it automatically handles file closure, even through exceptions.

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

Also, remember to fix your getscore()method so it doesn't always return 0. If you want it to printthe score as well, put the printstatement before the return.

另外,请记住修复您的getscore()方法,使其不总是返回 0。如果您也希望它print得分,请将print语句放在return.

回答by TigerhawkT3

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 openbuilt-in function.Do it like this.

首先,你应该问清楚你的问题,让别人理解。要将文本添加到文本文件中,你总是可以使用open内置函数。这样做。

>>> 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/

就是这样。如果需要进一步帮助,请尝试此网站。 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.

您还可以为游戏使用 for 循环来打印所有分数。自己试试这个吧。它会更有趣。

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.

现在尝试调用它python 3.4.2。好吧,我使用 .So ,如果遇到错误,请尝试检查字符串格式与您使用的 python 版本是否有任何不同。