None类型对象不是iterab

2024-06-16 13:03:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

因此,我的任务要求我使用一个导入的模块,该模块包含一个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))

Tags: 模块文件函数truereturndefpromptfile
1条回答
网友
1楼 · 发布于 2024-06-16 13:03:30

必须返回文件对象本身:

return open(input(prompt),openMode)

还有一些评论。你的代码大部分没有意义。在

  1. safeOpen中,有一个无休止的循环,但在第一次迭代之后无条件地保留它。你根本不需要这个循环。在
  2. safeOpen返回文件对象或错误消息。通常,函数应该总是返回相似类型的对象,并使用异常发出错误信号。在
  3. safeOpen包含异常,因此比内置的open更不安全。在
  4. inputFile.predicate试图从file对象inputFile读取一个名为predicate的属性。这将产生一个AttributeError,因为不存在这样的谓词。如果要将谓词函数传递给函数,请将其称为predicate(object)。在
  5. predicate == True仅当predicate是一个布尔值时才有效,这不是您想要的。在
  6. 行计数实际上并不计算复制的行数。在

相关问题 更多 >