what happens when the file begin read is too big for all lines to be read with "readlines()"

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Nov 20 00:26:34 EST 2005


On Sun, 20 Nov 2005 16:10:58 +1100, Steven D'Aprano wrote:

> def get_line(filename, token):
>     """Returns the next line following a token, or None if not found.
>     Leading and trailing whitespace is ignored when looking for
>     the token.
>     """
>     fp = file(filename, "r")
>     for line in fp:
>         if line.strip() == token:
>             break
>     else:
>         # runs only if we didn't break
>         print "Token not found"
>         result = None
>     result = fp.readline()  # read the next line only 
>     fp.close() 
>     return result

Correction: checking the Library Reference, I find that this is
wrong. The reason is that file objects implement their own read-ahead
buffer, and mixing calls to next() and readline() may not work right.

See http://docs.python.org/lib/bltin-file-objects.html

Replace the fp.readline() with fp.next() and all should be good.


-- 
Steven.




More information about the Python-list mailing list