2014-09-26 92 views
-1

我是Python的学习者(Windows 7上的Python 3.4)。当我在pycharm IDE中运行以下代码时,它工作正常,但是当它在codeeval.com challenge中作为解决方案提交时,它会给出错误IOError:[Errno 2]没有这样的文件或目录:'D:/ Trial/simple.txt”。为什么这样?。 在线解释器(Codeeval提交窗口)读取位于本地磁盘上的文件的正确方式是什么?从本地磁盘读取文件

path = "D:/Trial/simple.txt" 
file = open(path,"r+") 
age = file.read().split() 
for i in range(0,len(age)): 
    if int(age[i]) <= 2: 
     print("Still in Mama's arms") 
    if 4 == int(age[i]) == 3: 
     print("Preschool Maniac") 
    if 5 <= int(age[i]) >= 11: 
     print("Elementary school") 
    if 12 <= int(age[i]) >= 14: 
     print("Middle school") 
    if 15 <= int(age[i]) >= 18: 
     print("High school") 
    if 19 <= int(age[i]) >= 22: 
     print("College") 
    if 23 <= int(age[i]) >= 65: 
     print("Working for the man") 
    if 66 <= int(age[i]) >= 100: 
     print("The Golder years") 
file.close() 
+0

大多数情况下,输入是通过'stdin'提供的 – dawg 2014-09-27 00:08:32

+0

我怀疑codeeval解释器不允许你读取文件。它当然无法从您的计算机读取文件,并且它可能不会允许您从服务器读取文件(出于安全原因)。 – Blckknght 2014-09-27 01:11:32

回答

0

您的链接条件将不会做你期望的。 a compare b compare c == a compare b and b compare c。所以4 == int(age[i]) == 3永远不会是真的,并且5 <= int(age[i]) >= 11 == int(age[i]) >= 11

您没有指定年龄是全部在一行上还是在单独一行上。无论哪种方式,以下应该工作。请注意,可以直接遍历列表而不使用range

import sys 
ages = sys.stdin.read().split() 
for age in sys.stdin.read().split(): 
    age = int(age) 
    if age <= 2: 
     print("Still in Mama's arms") 
    if 3 <= age <= 4: 
     print("Preschool Maniac") 
    if 5 <= age <= 11: 
     print("Elementary school") 
    ...