Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 试图对导致AttributeError的函数的结果使用read或readlines方法_Python_Attributeerror - Fatal编程技术网

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())

你需要学习返回值是如何工作的…非常感谢你,只是有点困惑。