[Tutor] Uniform 'for' behavior for strings and files

Kent Johnson kent37 at tds.net
Tue Jun 10 00:16:51 CEST 2008


On Mon, Jun 9, 2008 at 5:26 PM, Shrutarshi Basu <technorapture at gmail.com> wrote:
> If I do the following:
>
> for item in block:
>
> where block is a file, then item becomes each line of the file in turn
> But if block in a large string (let's say the actual text that was in
> the file), item becomes each character at a time. Is there a way to
> have a uniform iteration irrespective of whether block is a file or
> string (ideally one \n-delimited line at a time)?

I would make a smart iterator that distinguishes between a file and a
string. For example (untested):

def lineIter(fileOrString):
  if isinstance(fileOrString, file):
    return iter(fileOrString)
  return iter(fileOrString.splitlines())

Now you can say
  for item in lineIter(block):

and get lines whether block is a file or a string.

Note that lines returned from a file will include newlines while those
from a string will not.

Kent


More information about the Tutor mailing list