![]() |
|
|
+ Search |
![]()
|
Jun 13th, 2002 06:39
Michael Chermside,
As of Python 2.1, there is a REALLY easy way to do this... the "for line
in file" idiom. Here is a simple example:
First, we'll define a simple 'processLine' function for testing. This
will simply calculate the average line length, but any kind of
processing would be OK:
Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> linesSeen = totalLength = 0
>>> def processLine( line ):
... global linesSeen, totalLength
... linesSeen += 1
... totalLength += len(line)
...
>>> def printResult():
... global linesSeen, totalLength
... print 'Average line length: %s' % (totalLength / linesSeen)
...
And the processing itself is incredibly trivial:
>>> f = file('README.txt')
>>> for line in f:
... processLine( line )
...
>>> printResult()
Average line length: 42