Python 试图对导致AttributeError的函数的结果使用read或readlines方法
我需要一些指导,因为我对为什么不能对函数的结果执行方法感到困惑 非常感谢您的帮助。谢谢 导入系统Python 试图对导致AttributeError的函数的结果使用read或readlines方法,python,attributeerror,Python,Attributeerror,我需要一些指导,因为我对为什么不能对函数的结果执行方法感到困惑 非常感谢您的帮助。谢谢 导入系统 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", fil
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:“function”对象没有属性“read”您将文件句柄
返回给了主程序,但主程序忽略了句柄。然后设置testfile
以引用函数对象open\u file
。函数对象没有read
方法,因此会出现错误
尝试将此修复作为主要代码块:
testfile = open_file('/users/stefan_trinh1991/documents/programming/python/py3e_source/chapter07/trivia.txt','r')
print(testfile.read())
你需要学习返回值是如何工作的…非常感谢你,只是有点困惑。