我需要一些指导,因为我对为什么不能对函数的结果执行方法感到困惑
非常感谢您的帮助。谢谢
导入系统
import sys
def open_file(file_name, mode):
"""This function opens a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("unable to open the file", file_name, "ending program. \n", e)
input("\n\nPress Enter to Exit")
sys.exit()
else:
return the_file
open_file('/users/stefan_trinh1991/documents/programming/python/py3e_source/chapter07/trivia.txt','r')
testfile = open_file
print(testfile.read())
它会导致出现以下错误
回溯(最近一次呼叫最后一次): 文件“/Users/stefan_trinh1991/Documents/Programming/Python/VS CWD/Trivia Challenge Game.py”,第48行,在 打印(testfile.read()) AttributeError:“函数”对象没有属性“读取”
您将文件句柄
the_file
返回给主程序,但主程序忽略了该句柄。然后设置^{cd2>}以引用函数对象^{cd3>}。函数对象没有read
方法,因此出现错误尝试将此修复作为主要代码块:
相关问题 更多 >
编程相关推荐