From: Raymond Hettinger Date: Tue, 28 Jun 2005 00:18:10 +0000 (+0000) Subject: Note that file objects are iterable. X-Git-Tag: v2.4.2c1~155 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=f7955af62f83dd44c4c6d9b495c0096cf4a8cd74;p=thirdparty%2FPython%2Fcpython.git Note that file objects are iterable. --- diff --git a/Doc/tut/tut.tex b/Doc/tut/tut.tex index 7c41a890297f..09fd2f077e39 100644 --- a/Doc/tut/tut.tex +++ b/Doc/tut/tut.tex @@ -3166,6 +3166,21 @@ entire file in memory. Only complete lines will be returned. ['This is the first line of the file.\n', 'Second line of the file\n'] \end{verbatim} +An alternate approach to reading lines is to loop over the file object. +This is memory efficient, fast, and leads to simpler code: + +\begin{verbatim} +>>> for line in f: + print line, + +This is the first line of the file. +Second line of the file +\end{verbatim} + +The alternative approach is simpler but does not provide as fine-grained +control. Since the two approaches manage line buffering differently, +they should not be mixed. + \code{f.write(\var{string})} writes the contents of \var{string} to the file, returning \code{None}.