2014-09-26 148 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") 
    ...