while c = f.read(1)

Robert Kern rkern at ucsd.edu
Fri Aug 19 02:04:36 EDT 2005


Greg McIntyre wrote:
> I have a Python snippet:
> 
>   f = open("blah.txt", "r")
>   while True:
>       c = f.read(1)
>       if c == '': break # EOF
>       # ... work on c
> 
> Is some way to make this code more compact and simple? It's a bit
> spaghetti.

That's not spaghetti. Not even close.

In any case, is there a reason you are reading one character at a time 
instead of reading the contents of the file into memory and iterating 
over the resulting string?

   f = open('blah.txt', 'r')
   text = f.read()
   f.close()

   for c in f:
       # ...

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.
       """
       # 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()

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list