我用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
我在运行它时一直收到以下错误消息:
^{pr2}$47号线,英寸 字符串=文件.read() IOError:文件未打开进行读取
有人能帮我吗?在
问题是您没有定义
file_n
;而是定义了file_name
。您只需将该行更改为open(file_name, "r")
。在相关问题 更多 >
编程相关推荐