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))
4

1 回答 1

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. 行数实际上并不计算复制的行数。
于 2012-04-15T21:11:46.253 回答