Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 试图打开文件时出现名称错误_Python_File_Syntax Error - Fatal编程技术网

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

Python 试图打开文件时出现名称错误,python,file,syntax-error,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 "+na

我用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:文件未打开以进行读取


有人能帮我一下吗?

问题是你没有定义
文件;您定义了
文件名
。您只需将该行更改为
open(file\u name,“r”)

file\u n
应该是
file\u name
我假设?行
file=open(file\u n,“r”)
应该是
file=open(file\u name,“r”)
创建文件需要更改什么@Yaroslav Admin@James Tobini注意到了这一点,并对其进行了更改,但我仍然收到一条错误消息string=file.read()IOError:file not open for readingi我意识到以前但现在我收到了这条错误消息Traceback(最近一次调用最后一次):string=file.read()IOError:文件未打开以供读取。您一定遗漏了其他内容。你能看到我可能错过的东西吗