faqts : Computers : Programming : Languages : Python : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

36 of 43 people (84%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How do I process a file line-by-line?
How about a simple example of using a file iterator.

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