这是我的代码打开文件;我想它包含一个名字和一个数字:试图打开.txt文件,但不断收到错误信息
file_n = "Class_" + str(num_class) + ".txt"
file = open(file_n,"r")
string = file.read()
file.close()
这也是我不断收到错误消息,我无法工作,如何解决它:
file = open(file_n,"r")
IOError: [Errno 2] No such file or directory: 'Class_2.txt'
有人可以告诉我为什么会发生这种情况并解决它吗? IM仍然很困惑 这是我的全部代码:
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 = {}
看起来像错误发生的原因是“Class_2.txt”不是现有文件或目录的名称。尝试一个不同的名字。 – Kevin
很可能,您的文件不存在于代码正在查看的目录中。您的代码所考虑的目录是第一个python脚本启动的目录。 –
查看当前目录 进口OS 打印(os.getcwd()) –