[Edu-sig] Teaching about files
Jaime E. Villate
villate at gnu.org
Sat Nov 13 18:10:12 CET 2004
On Sun, Nov 07, 2004 at 05:36:14PM -0500, Kent Johnson wrote:
>
> So my question is, am I missing something here? Is f.read(n) important?
> I want to de-emphasize f.read(n) and ignore f.readline(n), and emphasize
> 'for line in f:', with f.read(), f.readline() and f.readlines() also
> covered.
The "Python Cookbook" (Edited by A. Matelli & David Ascher, O'Reilly, 2002)
has a very nice section on that topic.
'for line in f:' is really the best method. The fact that it was only
introduced in Python 2.2 might explain why you still find examples
where it is not used or not given enough emphasis.
readlines can fail or become very slow with big files, because it
reads the whole file and returns a list of lines. Python 2.1
introduced xreadlines that does the same job using a limited amount of
memory. Since Python 2.2, those methods can be replaced by
'for line in f:'.
read is very useful when you need to access some specific bytes in a
file rather than a line, or if you're reading a binary file where the
concept of line does not exist.
Regards,
Jaime
More information about the Edu-sig
mailing list