Search code examples
pythonattributeerror

Trying to use read or readlines method on a result from a function causing a AttributeError


I need some guidance as I am getting confused to why I cannot perform a method on the result of a function.

would appreciate any help. thanks

import sys

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

it causes the following error to come up.

Traceback (most recent call last): File "/Users/stefan_trinh1991/Documents/Programming/Python/VS CWD/Trivia Challenge Game.py", line 48, in print(testfile.read()) AttributeError: 'function' object has no attribute 'read'


Solution

  • You returned the file handle the_file to your main program, but the main program ignored the handle. You then set testfile to refer to the function object open_file. The function object does not have a read method, hence the error.

    Try this repair as your main block of code:

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