[Tutor] How to write a function which reads files

Chris Warrick kwpolska at gmail.com
Tue Aug 7 09:23:47 EDT 2018


On Tue, 7 Aug 2018 at 15:07, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> def FileReader(file_path):
>     with open(file_path) as file_object:
>         contents = file_object.read
>         return contents
>
> print(FilePrinter("C:\\Users\\...\\MyFile.txt")) # path shortened for
> better readability
>
> I got this error message:
>
> <built-in method read of _io.TextIOWrapper object at 0x000001CA44448558>

You forgot the parentheses (), and are returning a reference to the
function instead of calling it and returning its result. Do this:
        contents = file_object.read()

Also, consider using snake_case instead of PascalCase for your
function name, since the latter is typically used for classes, and
perhaps call it read_file to better describe it?

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16


More information about the Tutor mailing list