iterators and generators, is this the Python Way???

Michael Schneider michaels at
Wed Sep 11 22:17:05 EDT 2002

Hello All.

I just updated my python to 2.2 and noticed that generators, and 
iterators were in there.

I often parse through many files (one at a time), and wanted the speed 
of read,  and
the convience of   for x in myGen:

The code below works just fine,  could you review this code against the 
intent of
iterators and generators.


# Goal:
#      Process files quickly, by reading the file in to memory in one 
#      the adding iterator behavior
#      Michael Schneider

from __future__ import generators

import sys
import os
from stat import *

class FastFile:
    def __init__(self, filename):
        """ Read in entire file into memory"""
        f = open(filename, 'r')
        fileContents =;
        self.lines = fileContents.split('\n')
    def  __iter__(self):
        return self.fastFileGen()

    def fastFileGen(self):
        for line in self.lines:
                yield line

# usage

        myFile = FastFile(filename)
    except IOError, msg:
        print, filename , " could not open "
        return 1

    # Process each line in the file
    for line in myFile:

More information about the Python-list mailing list