2016-02-25 63 views
1

这是我的代码打开文件;我想它包含一个名字和一个数字:试图打开.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 = {} 
+0

看起来像错误发生的原因是“Class_2.txt”不是现有文件或目录的名称。尝试一个不同的名字。 – Kevin

+1

很可能,您的文件不存在于代码正在查看的目录中。您的代码所考虑的目录是第一个python脚本启动的目录。 –

+4

查看当前目录 进口OS 打印(os.getcwd()) –

回答

1

确保您的Python代码就在于你的txt文件在同一目录。

因此,它应该是这样的: enter image description here

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


正如1001010说,你可以通过做检查当前目录:

import os 
print(os.getcwd()) 
+0

为什么我得到了一个downvote?如果我说错了什么,我想解决它,为未来的读者,*请*。 – gsamaras

+0

对不起,即时通讯新的这个我并不意味着它生病尝试,并改变它 – joel

+0

这是一个良好的开始@joel,检查答案,并接受最好的。 – gsamaras

1

像凯文和弗拉维提到Class_2.txt的目录是最有可能不是在您的脚本所在的目录。

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