尝试打开文件时出现名称错误

时间:2016-02-25 19:02:52

标签: python file syntax-error

我已经在Python中进行了测验并尝试将测验的分数与用户的名称一起保存在.txt文件中,但我不断收到错误消息,而我似乎无法找出原因。

这是我的代码:

import random

import json

score = 0

turn = 1

turn = turn + 1

name = raw_input("what is your name?")

num_class = input("What class are you in? (1,2,3)")

print ("hello "+name+" have fun and good luck!")

for turn in range(10):


    randnum_1 = random.randint(1,10)
    randnum_2 = random.randint(1,10)
    operators = ["+", "-", "*"]
    operator_picked = operators[random.randint(0,2)]
    human_answer = raw_input("What is " + str(randnum_1) +" "+ operator_picked +" " + str(randnum_2) + "?")
    correct_answer = str((eval(str(randnum_1) + operator_picked + str(randnum_2))))


    if correct_answer == human_answer :
        score = score+1
        print ("Correct!")

    else:
        print ("Incorrect!" +"The correct answer is " + str(correct_answer))


print("\nYour score was " + str(score)+ "/10")


file_name = ("Class_" + str(num_class) + ".txt")

file = open(file_n,"r")

string = file.read()

file.close()

dict = {}

try:

    dict = json.loads(string)

except:

    pass

try:

    dict[name].append(score)

except:

    dict[name] = score

运行时我不断收到此错误消息:

Traceback (most recent call last):

第47行,在     string = file.read() IOError:文件未打开以供阅读

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

问题是你没有定义file_n;你定义了file_name。您只需将该行更改为open(file_name, "r")