On Tue, Mar 22, 2016 at 10:05 PM, BartC <b...@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
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to