2012-04-15 117 views
0

在別人告訴我再搜索一下網頁之前,我已經搜索了一個多小時了。無類型對象不可迭代

所以我的任務需要我使用一個導入的模塊,其中包含一個safeOpen函數,用於打開主模塊的文件selectiveFileCopy。但是,當我調用safeOpen函數時,它說我試圖打開的文件是一個None類型,因此不可迭代。我不確定這是爲什麼。

下面是一些代碼:

def safeOpen(prompt, openMode, errorMessage): 
    while True: 
     try: 
     open(input(prompt),openMode) 
     return 
     except IOError: 
     return(errorMessage) 

def selectivelyCopy(inputFile,outputFile,predicate): 
    linesCopied = 0 
    for line in inputFile: 
     outputFile.write(inputFile.predicate) 
     if predicate == True: 
     linesCopied+=1 
    return linesCopied 


inputFile = fileutility.safeOpen("Input file name: ", "r", " Can't find that file") 
outputFile = fileutility.safeOpen("Output file name: ", "w", " Can't create that file") 
predicate = eval(input("Function to use as a predicate: ")) 
print(type(inputFile)) 
print("Lines copied =",selectivelyCopy(inputFile,outputFile,predicate)) 
+0

錯誤發生在哪條線上? – Cameron 2012-04-15 21:10:56

回答

4

你必須返回文件對象本身:

return open(input(prompt),openMode) 

一些更多的評論。代碼的大部分內容都沒有意義。

  1. safeOpen中,您有一個無限循環,但是無條件地在第一次迭代之後離開它。根本不需要這個循環。
  2. safeOpen返回文件對象或錯誤消息。通常,函數應該總是返回類似類型的對象,並使用異常來發出錯誤信號。
  3. safeOpen吞嚥異常,因此比內建open安全。
  4. inputFile.predicate嘗試從文件對象inputFile讀取名爲predicate的屬性。這將產生一個AttributeError,因爲不存在這樣的謂詞。如果要將謂詞函數傳遞給該函數,請將其稱爲predicate(object)
  5. predicate == True只適用於predicate是一個布爾值,這不是你想要的。
  6. 行計數實際上不計算複製的行數。
+0

1-3) 老實說,我只是按照我的教授在他的作業中指定的內容。他要求循環,嘗試和返回語句,並基本從課程中查看他的代碼並嘗試模仿它。 4) 固定that..kind 5) 我想要什麼? 6) 修復了這個問題 – 2012-04-15 22:29:09

+0

我想我忘了提及另外一個導入的模塊,叫做choices,帶有返回布爾值的函數。這些是我的教授的「謂詞」。指定。 – 2012-04-15 22:36:17