2012-04-15 103 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