The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Chris Angelico rosuav at gmail.com
Tue Mar 22 07:15:40 EDT 2016


On Tue, Mar 22, 2016 at 10:05 PM, BartC <bc at freeuk.com> wrote:
> But out of interest, how would /you/ write a function that takes a file-spec
> and turns it into an in-memory string? And what would its use look like?

def read_file(fn, *a, **kw):
    with open(fn, *a, **kw) as f:
        return f.read()

Usage:

script = read_file(".bashrc")
data = read_file("Ellalune_AlicePortrait.jpg", "rb")
decoded = read_file("greek.srt", encoding="ISO-8859-7")

If there's any problem with reading the file, an exception will be
raised. Also, thanks to the 'with' block, I'm guaranteed that the file
will have been closed before read_file() returns, which means I can
immediately go and write to the file without a conflict.

ChrisA



More information about the Python-list mailing list