尝试对导致 AttributeError 的函数的结果使用 read 或 readlines 方法

Trying to use read or readlines method on a result from a function causing a 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", 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 挑战 Game.py”,第 48 行,在 打印(testfile.read()) AttributeError: 'function' 对象没有属性 'read'

您将文件句柄 the_file 返回给主程序,但主程序忽略了该句柄。然后设置 testfile 以引用 函数对象 open_file。函数对象没有 read 方法,因此出现错误。

尝试将此修复作为您的主要代码块:

testfile = open_file('/users/stefan_trinh1991/documents/programming/python/py3e_source/chapter07/trivia.txt','r')
print(testfile.read())