从文本文件读取语法错误/想要将文本文件中的每一行分配到不同的列表

时间:2017-10-03 12:12:20

标签: python file text

我正在尝试制作一个数学游戏,我想实现一个高分跟踪器,它将人的高分以及他们的名字保存在文本文件中,并且它为每个玩家做到了这一点。如果玩家再次玩,则可以从文本文件中调出他的高分。到目前为止,这是我的代码:

import random
def game():
    while 1:
        c1 = input("Would you like to play from the beginning?").lower()
        if c1 == "yes":
            lvl1()
        elif c1 == "no":
            print("Your score was:", score)
            main()
            break
        else:
            game()
    quit()
def lvl1():
    print("LEVEL 1")
    global score
    score = 0
    operators = ("+","-")
    while 1:
        No1 = random.randint(1,10)
        No2 = random.randint(1,10)
        Op = random.choice(operators)
        if Op == "+":
            A1 = No1 + No2
            print("What is", No1, Op, No2,"?")
            answer = float(input("Enter your answer"))
        elif Op == "-":
            A1 = No1 - No2
            print("What is", No1,Op,No2,"?")
            answer = float(input("Enter your answer"))
        if answer == A1:
            print("Correct!")
            score = score + 1
            print(score)
        else:
            print("Incorrect! Try again...")
            game()
        if score == 5:
            break
    print("Congratulations on making it to level 2!")
    lvl2()
def lvl2():
    print("LEVEL 2")
    global score
    score = 5
    operators = ("+","-","x")
    while 1:
        No1 = random.randint(1,15)
        No2 = random.randint(1,15)
        Op = random.choice(operators)
        if Op == "+":
            A1 = No1 + No2
            print("What is", No1, Op, No2,"?")
            answer = float(input("Enter your answer"))
        elif Op == "-":
            A1 = No1 - No2
            print("What is", No1,Op,No2,"?")
            answer = float(input("Enter your answer"))
        else:
            A1 = No1 * No2
            print("What is", No1,Op,No2,"?")
            answer = float(input("Enter your answer"))
        if answer == A1:
            print("Correct!")
            score = score + 1
            print(score)
        else:
            print("Incorrect! Try again...")
            game()
        if score == 10:
            break
    print("Congratulations on making it to level 3!")
    lvl3()
def lvl3():
    print("LEVEL 3")
    global score
    score = 10
    operators = ("+","-","x")
    while 1:
        No1 = random.randint(10,50)
        No2 = random.randint(10,50)
        Op = random.choice(operators)
        if Op == "+":
            A1 = No1 + No2
            print("What is", No1, Op, No2,"?")
            answer = float(input("Enter your answer"))
        elif Op == "-":
            A1 = No1 - No2
            print("What is", No1,Op,No2,"?")
            answer = float(input("Enter your answer"))
        else:
            A1 = No1 * No2
            print("What is", No1,Op,No2,"?")
            answer = float(input("Enter your answer"))
        if answer == A1:
            print("Correct!")
            score = score + 1
            print(score)
        else:
            print("Incorrect! Try again...")
            game()
        if score == 15:
            break
    print("Congratulations on making it to level 4!")
    lvl4()
def lvl4():
    print("LEVEL 4")
    global score
    score = 15
    operators = ("+","-","x")
    while 1:
        No1 = random.randint(10,100)
        No2 = random.randint(10,100)
        Op = random.choice(operators)
        if Op == "+":
            A1 = No1 + No2
            print("What is", No1, Op, No2,"?")
            answer = float(input("Enter your answer"))
        elif Op == "-":
            A1 = No1 - No2
            print("What is", No1,Op,No2,"?")
            answer = float(input("Enter your answer"))
        else:
            A1 = No1 * No2
            print("What is", No1,Op,No2,"?")
            answer = float(input("Enter your answer"))
        if answer == A1:
            print("Correct!")
            score = score + 1
            print(score)
        else:
            print("Incorrect! Try again...")
            game()
        if score == 20:
            break
    print("Congratulations! You have completed the game.")
    main()
def gethighscore():
    # Default high score
    highscore = 0

    # Try to read the high score from a file
    try:
        highscorefile = open("highscore.txt", "r")
        name = str(highscorefile.read())
        highscore = int(highscorefile.read())
        highscorefile.close()
        print("The high score is", highscore)
    except IOError:
        # Error reading file, no high score
        print("There is no high score yet.")


    return highscore


def savehighscore(new_high_score):
    try:
        # Write the file to disk
        highscorefile = open("highscore.txt", "w")
        L = [name, new_high_score]
        highscorefile.write(str(L))
        highscorefile.close()
    except IOError:
        # Hm, can't write it.
        print("Unable to save the high score.")


def main():
    # Get the high score
    highscore = gethighscore()
    if score < highscore:
        print("Yea! New high score!")
        savehighscore(score)
    else:
        print("Better luck next time.")


print("Welcome to the maths game.")
name = input("What is your name?")
print("IT'S TIME!")
lvl1()
quit()

我目前收到此错误:

Your score was: 2
Traceback (most recent call last):
  File "D:\A level computer science\Maths game.py", line 182, in <module>
    lvl1()
  File "D:\A level computer science\Maths game.py", line 37, in lvl1
    game()
  File "D:\A level computer science\Maths game.py", line 9, in game
    main()
  File "D:\A level computer science\Maths game.py", line 171, in main
    highscore = gethighscore()
  File "D:\A level computer science\Maths game.py", line 146, in gethighscore
    highscore = int(highscorefile.read())
ValueError: invalid literal for int() with base 10: ''

1 个答案:

答案 0 :(得分:1)

列表不能直接写入文件,而是在以下行中:

highscorefile.write(str(L))

它被转换为字符串。当您在gethighscore()中阅读文件时,结果也是字符串不是列表

您可以通过多种方式保存和阅读高分。让我告诉你一个非常简单的方法:

名为ast的第一个导入模块。然后更改您的gethighscore()

def gethighscore():
    # Default high score
    highscore = 0

    # Try to read the high score from a file
    try:
        highscorefile = open("highscore.txt", "r")
        fileContent = highscorefile.read()
        highscorefile.close()

        # This converts a string list to list

        L = ast.literal_eval(fileContent)
        name = L[0]
        highscore = L[1]
        print("The high score is", highscore)
    except IOError:
        # Error reading file, no high score
        print("There is no high score yet.")


    return highscore

希望它有所帮助!如果您仍然有任何问题请注释。