[Python-Dev] Use for enumerate()

Patrick K. O'Brien pobrien@orbtech.com
Fri, 26 Apr 2002 18:31:29 -0500


[Guido van Rossum]
>
>     def getline(filename, lineno):
> 	if lineno < 1:
> 	    return ''
> 	lineno -= 1
> 	f = open(filename)
> 	for i, line in enumerate(f):
> 	    if i == lineno:
> 		break
> 	else:
> 	    line = ''
> 	f.close()
> 	return 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.

I doubt it's faster and it's barely less code (I had to resist the urge to
add a try/finally), but here is the only decent variation I could come up
with:

def getline(filename, lineno):
    line = ''
    if lineno > 0:
        lineno -= 1
        f = open(filename)
        for i, s in enumerate(f):
            if i == lineno:
                line = s
                break
        f.close()
    return line

I'm ready to give up now. What's the fastest, smallest solution?

---
Patrick K. O'Brien
Orbtech