如何使用Python在文本文件中读取和写入多个值?

永无止境的循环

因此,我正在尝试使用python编写分数较高的文本文件,以便在其他人打开程序时可以读取。我之前在C ++中已经做到了,它看起来像这样:

    void main()
{
    //Declare local variables
    int High_Score[5];
    int Rank;

    string High_Score_Name[5];

    //Initialize a high score at 0
    High_Score[4] = 0;

    //Input the high scores from a file
    ifstream Input_High_Scores;
    Input_High_Scores.open("High_Scores.txt");

    for (int i = 0; i < 5; i++)
    {
        Input_High_Scores >> High_Score[i];
        Input_High_Scores >> High_Score_Name[i];
    }
    Input_High_Scores.close();

    if (High_Score[4] == 0)
    {
        //Initialize local variables
        High_Score[0] = 999999999;
        High_Score[1] = 40000;
        High_Score[2] = 37000;
        High_Score[3] = 30000;
        High_Score[4] = 25000;
        High_Score_Name[0] = "Developer";
        High_Score_Name[1] = "Adam";
        High_Score_Name[2] = "Nastasia";
        High_Score_Name[3] = "Nicolas";
        High_Score_Name[4] = "Dani";
    }
}

我需要的是一个可以在Python中完成此工作的版本。我找到了一种在文本文件中保存1个值的方法,但我希望它总共保存10个值。5个名字和5个分数。我还需要知道如何在程序中读取这些值。这是我到目前为止的内容:

    # Trivia game created by NeverEndingCycle

Start = ""
Exit = ""
Score = int(0)
Next = ""
HighScore = int(0)


def GetHighScore():
    # Default high score
    HighScore = 0

    # Try to read the high score from a file
    try:
        high_score_file = open("high_score.txt", "r")
        HighScore = int(high_score_file.read())
        high_score_file.close()
        print("The high score is", HighScore)
    except IOError:
        # Error reading file, no high score
        print("There is no high score yet.")
        print("")
    except ValueError:
        # There's a file there, but we don't understand the value.
        print("I'm confused. Starting with no high score.")

    return HighScore


def save_high_score(new_high_score):
    try:
        # Write the file to disk
        high_score_file = open("Highscore.txt", "w")
        high_score_file.write(str(new_high_score))
        high_score_file.close()
    except IOError:
        # Hm, can't write it.
        print("ERROR --- Unable to save the high score.")


def CheckForHighScore():
    global Score
    # Get the high score
    high_score = GetHighScore()

    # Get the score from the current game
    current_score = 0
    try:
        current_score = Score
    except ValueError:
        # Error
        print("___ERROR___")

    # See if we have a new high score
    if current_score > high_score:
        # We do! Save to disk
        global Exit
        print("Yea! New high score!")
        save_high_score(current_score)
        Exit = input("Press ENTER to exit")
    else:
        global Exit
        print("No new Highscore, Better luck next time.")
        Exit = input("Press ENTER to exit")


def ShowScore():
    global Score
    global Next
    print("")
    print("You now have", Score, "Point(s).")
    Next = input("Press ENTER to continue to the next Question.")


def Q1():
    global Score
    print("")
    print("Question 1.")
    print("What type of variable is a String? (1 Point)")
    print("")
    print("1. Letters")
    print("2. Numbers")
    print("3. Decimals")
    print("4. A String is not a varible.")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 1
        print("")
        print("Correct! 1 point has been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q2():
    global Score
    print("")
    print("Question 2.")
    print("(1 Point)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")
    Answer = input("What is your answer? ")

    if Answer == "1":
        Score = Score + 1
        print("")
        print("Correct! 1 point has been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q3():
    global Score
    print("")
    print("Question 3.")
    print("(1 Point)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 1
        print("")
        print("Correct! 1 point has been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q4():
    global Score
    print("Question 4.")
    print("(1 Point)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 1
        print("")
        print("Correct! 1 point has been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q5():
    global Score
    print("Question 5.")
    print("(5 Points)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 5
        print("")
        print("Correct! 5 points have been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q6():
    global Score
    print("")
    print("Question 6.")
    print("(2 Points)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 2
        print("")
        print("Correct! 2 points have been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q7():
    global Score
    print("")
    print("Question 7.")
    print("(2 Points)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 2
        print("")
        print("Correct! 2 points have been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q8():
    global Score
    print("")
    print("Question 8.")
    print("(2 Points)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 2
        print("")
        print("Correct! 2 points have been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q9():
    global Score
    print("Question 9.")
    print("(2 Points)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 2
        print("")
        print("Correct! 2 points have been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Q10():
    global Score
    print("")
    print("Question 10.")
    print("(10 Points)")
    print("")
    print("1. ")
    print("2. ")
    print("3. ")
    print("4. ")
    print("")

    Answer = input("What is your answer? ")
    if Answer == "1":
        Score = Score + 10
        print("")
        print("Correct! 2 points have been added to your score!")
        print("")
    elif Answer == "2":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "3":
        print("")
        print("Incorrect. No points were added.")
        print("")
    elif Answer == "4":
        print("")
        print("Incorrect. No points were added.")
        print("")
    else:
        print("Incorrect. Choose an answer between 1 and 4 next time!")
    return Score


def Main():
    global Next
    Q1()
    ShowScore()

    Q2()
    ShowScore()

    Q3()
    ShowScore()

    Q4()
    ShowScore()
    print("")
    print("Bonus Question 5x Points!")

    Q5()
    ShowScore()
    print("")
    print("Last 5 questions! All points are double!")

    Q6()
    ShowScore()

    Q7()
    ShowScore()

    Q8()
    ShowScore()

    Q9()
    ShowScore()
    print("")
    print("Final Question 5x Points!")

    Q10()
    ShowScore()
    Next = input("Press ENTER to continue.")


Name = input("Please enter your name: ")
print("")
print("Welcome, %s, to NeverEndingCycle's Trivia Game!" % (Name))
print("")
Start = input("Press ENTER to begin playing!")
print("")

Main()

CheckForHighScore()

最后,如果我可以保留尽可能多的原始代码,那就太好了。我正在努力自学,到目前为止进展顺利。我的意思是,我需要了解解决我的问题的解决方案,否则我将不知道将来如何解决。

我对python还是很陌生-就像上周刚开始一样-我正在自学,所以对这是一个愚蠢的问题我深表歉意,但是我找不到任何解决方案。另外,我知道自己的格式很糟糕,正在研究中。

特拉辛

将数据追加到文件

此代码可用于将数据追加到文件,因此,如果文件存在,它将不会覆盖当前数据。“ a +”代表追加,加号表示如果文件不存在,它将创建一个文件。

high_score_file = open("Highscore.txt", "a+")

要将高分信息写入文件,只需更改第一行代码。请参阅“ a +”而不是“ w”。

high_score_file = open("Highscore.txt", "a+")
high_score_file.write(str(new_high_score)
high_score_file.close()

从文件读取数据

从文件读取数据很简单,这是一种读入数据的有效方法。它将逐行读取数据。另外,第一行还在只读模式下打开文件,因此给定了“ r”。这意味着您将无法对其进行写入。

high_score_file = open("Highscore.txt", "r")
for line in high_score_file:
    print(line, end='')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用 Python 读取文件并将其完全写入多个文本文件?

如何在python中同时读取和写入文本文件?

如何在Python中读取和写入文本文件的多行

如何在Python中读取多个nltk语料库文件并写入单个文本文件

如何从文本文件读取和写入整数?

如何使用 Pandas 在 Python 中读取文本文件

如何在文本文件中写入多个ArrayList

如何在Flutter中读取和写入文本文件

如何在文本文件中读取和写入用户列表

如何使用Shell脚本读取XML和写入文本文件?

如何使用C#向包含用户输入的文本文件写入和读取列表

我想在 python 中写入和读取文本文件的列表

如何读取文本文件,然后使用python将其拆分为多个文本文件?

如何在python和beautifulsoup中的文本文件中将多个for循环打印结果写入一行

如何从文本文件中读取一系列数字并使用python写入新行?

如何使用delphi从文本文件中读取/写入集合枚举

如何在R中读取多个文本文件

如何在Matlab中读取多个文本文件?

如何写入文本文件中的键和值并读回它们?

如何使用python将多个输入写入文本文件?

如何在 Python 中永久写入文本文件?

如何使用 CPP 在文本文件中写入

如何从文本文件中读取和存储数据

如何从文本文件中读取和保存数据?

在python中读取和分组文本文件的内容

如何从python中的文本文件中读取数字?

如何从 Python 3.9.6 中的文本文件中读取?

如何读取和替换文本文件一栏中的特定值?

我如何在多个文本文件中搜索模式并写入新的多个文本文件