在有人告诉我再搜索网页之前,我已经搜索了一个多小时。
所以我的作业要求我使用包含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 :(得分:4)
您必须返回文件对象:
return open(input(prompt),openMode)
更多评论。代码的大部分内容都没有意义。
safeOpen
中,您有一个无限循环,但无条件地在第一次迭代后离开它。你根本不需要这个循环。safeOpen
返回文件对象或错误消息。通常,函数应始终返回类似对象,并使用异常信号错误。safeOpen
吞下例外,因此不如内置open
安全。inputFile.predicate
尝试从文件对象predicate
中读取名为inputFile
的属性。这将产生AttributeError
,因为不存在这样的谓词。如果要将谓词函数传递给函数,请将其称为predicate(object)
。predicate == True
仅在predicate
为布尔值时才有效,这不是您想要的。