Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ed3cd7e

Browse files
committed
#13510: clarify that f.readlines() is note necessary to iterate over a file. Patch by Dan Riti.
1 parent 45fe62d commit ed3cd7e

3 files changed

Lines changed: 8 additions & 15 deletions

File tree

Doc/library/io.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ I/O Base Classes
298298
to control the number of lines read: no more lines will be read if the
299299
total size (in bytes/characters) of all lines so far exceeds *hint*.
300300

301+
Note that it's already possible to iterate on file objects using ``for
302+
line in file: ...`` without calling ``file.readlines()``.
303+
301304
.. method:: seek(offset, whence=SEEK_SET)
302305

303306
Change the stream position to the given byte *offset*. *offset* is

Doc/tutorial/inputoutput.rst

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -300,28 +300,17 @@ containing only a single newline. ::
300300
>>> f.readline()
301301
''
302302

303-
``f.readlines()`` returns a list containing all the lines of data in the file.
304-
If given an optional parameter *sizehint*, it reads that many bytes from the
305-
file and enough more to complete a line, and returns the lines from that. This
306-
is often used to allow efficient reading of a large file by lines, but without
307-
having to load the entire file in memory. Only complete lines will be returned.
308-
::
309-
310-
>>> f.readlines()
311-
['This is the first line of the file.\n', 'Second line of the file\n']
312-
313-
An alternative approach to reading lines is to loop over the file object. This is
314-
memory efficient, fast, and leads to simpler code::
303+
For reading lines from a file, you can loop over the file object. This is memory
304+
efficient, fast, and leads to simple code::
315305

316306
>>> for line in f:
317307
... print(line, end='')
318308
...
319309
This is the first line of the file.
320310
Second line of the file
321311

322-
The alternative approach is simpler but does not provide as fine-grained
323-
control. Since the two approaches manage line buffering differently, they
324-
should not be mixed.
312+
If you want to read all the lines of a file in a list you can also use
313+
``list(f)`` or ``f.readlines()``.
325314

326315
``f.write(string)`` writes the contents of *string* to the file, returning
327316
the number of characters written. ::

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,6 +1003,7 @@ Nicholas Riley
10031003
Jean-Claude Rimbault
10041004
Vlad Riscutia
10051005
Wes Rishel
1006+
Dan Riti
10061007
Juan M. Bello Rivas
10071008
Davide Rizzo
10081009
Anthony Roach

0 commit comments

Comments
 (0)