[Tutor] How to write a function which reads files

Mats Wichmann mats at wichmann.us
Tue Aug 7 18:39:08 EDT 2018



Question is already answered, just wanted to add a mini-note.


def FileReader(file_path):    with open(file_path) as file_object:
 contents = file_object.read        return contents
you /can/ return the read method here, which is what this typo does. And
the caller of the function can use it to read, as in:

print(FileReader("...path...")())

that is, since FileReader as originally written returns a callable, you
can call it.

However in this case, since the use of the file context manager (open
using "with" statement) does what it's supposed to, the read will fail,
and you get:

ValueError: I/O operation on closed file.

because as soon as the with statement is exited, things are cleaned up.
That's what context managers do.  That doesn't mean there are not cases
when you will want to return a function/method for use elsewhere, it's
part of the "Python is powerful because functions are first-class"
argument :)




More information about the Tutor mailing list