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

2024-04-27 02:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些指导,因为我对为什么不能对函数的结果执行方法感到困惑

非常感谢您的帮助。谢谢

导入系统

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:“函数”对象没有属性“读取”


Tags: theto方法函数namereadmodesys
1条回答
网友
1楼 · 发布于 2024-04-27 02:32:54

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

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

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

相关问题 更多 >