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

时间:2018-03-24 19:29:35

标签: python c++

所以,我正在尝试使用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很新 - 就像上周刚开始的那样 - 我正在自学,所以如果这是一个愚蠢的问题,我道歉,但我无法在任何地方找到解决方案。另外,我知道我的格式很糟糕,我正在努力。

2 个答案:

答案 0 :(得分:1)

将数据附加到文件

此代码可用于将数据附加到文件,因此,如果文件存在,它将不会覆盖当前数据。 “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='')

答案 1 :(得分:0)

据我所知,您希望将多行写入文本文件。 This page帮助了我。我建议用high_score_file.write(str(new_high_score))替换high_score_file.writelines([line1, line2, line3])。并为每一行写下您计划的10个值。