无类型对象不可迭代

时间:2012-04-15 21:08:57

标签: python python-3.x

在有人告诉我再搜索网页之前,我已经搜索了一个多小时。

所以我的作业要求我使用包含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))

1 个答案:

答案 0 :(得分:4)

您必须返回文件对象:

return open(input(prompt),openMode)

更多评论。代码的大部分内容都没有意义。

  1. safeOpen中,您有一个无限循环,但无条件地在第一次迭代后离开它。你根本不需要这个循环。
  2. safeOpen返回文件对象或错误消息。通常,函数应始终返回类似对象,并使用异常信号错误。
  3. safeOpen吞下例外,因此不如内置open安全。
  4. inputFile.predicate尝试从文件对象predicate中读取名为inputFile的属性。这将产生AttributeError,因为不存在这样的谓词。如果要将谓词函数传递给函数,请将其称为predicate(object)
  5. predicate == True仅在predicate为布尔值时才有效,这不是您想要的。
  6. 行计数实际上并不计算复制的行数。
相关问题