~ubuntu-branches/ubuntu/saucy/python2.7/saucy-proposed

« back to all changes in this revision

Viewing changes to Doc/tutorial/inputoutput.rst

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-05-15 19:15:16 UTC
  • mto: (36.1.23 sid)
  • mto: This revision was merged to the branch mainline in revision 87.
  • Revision ID: package-import@ubuntu.com-20130515191516-zmv6to904wemey7s
Tags: upstream-2.7.5
ImportĀ upstreamĀ versionĀ 2.7.5

Show diffs side-by-side

added added

removed removed

Lines of Context:
295
295
   >>> f.readline()
296
296
   ''
297
297
 
298
 
``f.readlines()`` returns a list containing all the lines of data in the file.
299
 
If given an optional parameter *sizehint*, it reads that many bytes from the
300
 
file and enough more to complete a line, and returns the lines from that.  This
301
 
is often used to allow efficient reading of a large file by lines, but without
302
 
having to load the entire file in memory.  Only complete lines will be returned.
303
 
::
304
 
 
305
 
   >>> f.readlines()
306
 
   ['This is the first line of the file.\n', 'Second line of the file\n']
307
 
 
308
 
An alternative approach to reading lines is to loop over the file object. This is
309
 
memory efficient, fast, and leads to simpler code::
 
298
For reading lines from a file, you can loop over the file object. This is memory
 
299
efficient, fast, and leads to simple code::
310
300
 
311
301
   >>> for line in f:
312
302
           print line,
314
304
   This is the first line of the file.
315
305
   Second line of the file
316
306
 
317
 
The alternative approach is simpler but does not provide as fine-grained
318
 
control.  Since the two approaches manage line buffering differently, they
319
 
should not be mixed.
 
307
If you want to read all the lines of a file in a list you can also use
 
308
``list(f)`` or ``f.readlines()``.
320
309
 
321
310
``f.write(string)`` writes the contents of *string* to the file, returning
322
311
``None``.   ::