[CentralOH] cStringIO

Joe Shaw joe at joeshaw.org
Wed Nov 6 15:01:21 CET 2013


Hi,

I'd probably also make use of contextlib.closing rather than managing the
file by itself.

with contextlib.closing(cStringIO.StringIO(s)) as f:
    # previous code here, no need to explicitly close() the file afterward

This ensures that the file is closed even in the case of error (and is,
IMO, cleaner than a try-finally block)

Joe


On Wed, Nov 6, 2013 at 8:07 AM, <jep200404 at columbus.rr.com> wrote:

> On Wed, 6 Nov 2013 11:36:52 +0800, iynaix <iynaix at gmail.com> wrote:
>
> > from functools import partial
> >
> > f = cStringIO.StringIO(s)
> > records = iter(partial(f.read, CHUNK_SIZE), '')
> > for r in records:
> >     print CHUNK_SIZE, repr(r)
> > f.close()
>
> Thanks! That's much better than my ugly code.
>
> >     print CHUNK_SIZE, repr(r)
>
> If one is going to print CHUNK_SIZE,
> one might as well do it outside the loop.
> I wanted to see the size of individual r's,
> particularly the last one which can be different
> than CHUNK_SIZE, hence the len(r) as follows.
>
>     print len(r), repr(r)
>
> > 3. file is a python builtin function, as an alias for open, not a good
> name
> > for a variable. :)
>
> Wow, that was pretty stupid of me. Thanks for catching that.
>
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> https://mail.python.org/mailman/listinfo/centraloh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/centraloh/attachments/20131106/4e4b7487/attachment.html>


More information about the CentralOH mailing list