file.readlines() question

jepler at unpythonic.net jepler at unpythonic.net
Sat Jun 1 04:05:06 CEST 2002


this finds a line in f with the substring s, using a readlines hint,
defaulting to 4096.  If found, it returns the line itself and the line
number (of the first match). Otherwise, it returns None.

Untested.  :)

def findit(f, s, hint=4096):
    lineno = 0
    while 1:
	chunk = f.readlines(hint)
	if not chunk: break
	for line in chunk:
	    lineno = lineno + 1
	    if string.find(line, s) != -1:
		return line, lineno

in newer Python, you could write
    def findit2(f, s):
	lineno = 0
	for line in f:
	    lineno = lineno + 1
	    if string.find(line, s) != -1:
		return line, lineno
because when you treat a file like an iterator, it yields each
successive line (a drag if you happen to think files are made out of bytes
<\u00bd wink>).  I think this is implemented with the efficiency of
readlines-sizehint internally.

Jeff





More information about the Python-list mailing list