尝试打开.txt文件,但不断收到错误消息

时间:2016-02-25 17:19:01

标签: python file

这是我打开文件的代码;我希望它包含一个名称和一个数字:

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]没有这样的文件或目录:' Class_2.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 = {}

2 个答案:

答案 0 :(得分:1)

确保您的Python代码与txt文件位于同一目录中。

所以它应该是这样的: enter image description here

当然这两个文件可以在不同的目录中,但是你应该在你的代码中提供txt文件的相关或绝对路径。

如1001010所述,您可以通过执行以下操作检查当前目录:

import os
print(os.getcwd()) 

答案 1 :(得分:1)

像Kevin和Flavian所提到的,Class_2.txt的目录很可能不是脚本所在的目录。

file_n = "/ActualDirectory/ofFile/Class_" + str(num_class) + ".txt"
相关问题