从本地磁盘读取文件

时间:2014-09-26 21:46:00

标签: python-3.x

我学习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()

1 个答案:

答案 0 :(得分: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")
    ...