while c = f.read(1)
Greg McIntyre
greg at puyo.cjb.net
Wed Aug 24 21:19:37 EDT 2005
Robert Kern wrote:
> > Robert> Please quote the message you are replying to. We have no
> > Robert> idea what "the 2nd option" is.
> >
> > I think he means the second option you presented
> >
> > If you must read one character at a time,
> >
> > def reader(fileobj, blocksize=1):
> > """Return an iterator that reads blocks of a given size from a
> > file object until EOF.
> > ...snip
> >
> > With a decent threaded news/mail reader, the thread provides
> > sufficient context, no?
>
> Not taking into account the python-list gateway or GMane. I see his
> message threaded directly under his original one.
>
> And dammit, I'm vain enough that if people are complimenting my code, I
> want to be sure about it. ;-)
Sorry Robert, I'm using Google Groups until I figure out the news
settings for our ISP at work (which is most unhelpful). I'm not used to
using it and the default 'Reply' option doesn't quote. :\ Not a good
excuse, I know.
Let's see... to summarise the responses I got, I liked yours the best,
Robert. It was:
def reader(fileobj, blocksize=1):
"""Return an iterator that reads blocks of a given size from a
file object until EOF.
"""
# Note that iter() can take a function to call repeatedly until
it
# receives a given sentinel value, here ''.
return iter(lambda: fileobj.read(blocksize), '')
f = open('blah.txt', 'r')
try:
for c in reader(f):
# ...
finally:
f.close()
I like it because I can make 'reader' a stock library function I can
potentially re-use and it removes complexity from the area where I want
to place the domain-specific logic (where I call reader()), which I
have a personal preference for.
Potentially the added comlexity of buffering larger chunks at a time
for efficiency could also be put into the reader() function to keep the
rest of the code super clean and neat.
More information about the Python-list
mailing list