[Python-Dev] Use for enumerate()
Guido van Rossum
Fri, 26 Apr 2002 17:26:59 -0400
Here's a cute use for enumerate(), now that it's checked in.
I was reading the section on files in the Python Cookbook manuscript.
It recommends using linecache() if you need to get a particular line
from a file. I agree that this is a good approach if you may need
multiple lines from the same file, but if you know that all you need
is one line from one file, linecache does too much (it reads the whole
file, and keeps all of it in memory).
A function that reads forward until the right line is of course easily
written for any version of Python; but enumerate() seems a
particularly good fit here since it avoids the need to have a separate
counter. This also shows how useful it is that files are iterators!
def getline(filename, lineno):
if lineno < 1:
lineno -= 1
f = open(filename)
for i, line in enumerate(f):
if i == lineno:
line = ''
Challenge 1: do it faster.
Challenge 2: do it with less code.
Challenge 3: do it faster and with less code.
Rules: the semantics must be the same: always close the file, return
'' for lineno out of range; lineno < 1 should not open the file.
--Guido van Rossum (home page: http://www.python.org/~guido/)