[Tutor] f.readlines(size)
Nancy Pham-Nguyen
nancyphng at yahoo.com
Mon Jun 5 18:53:23 EDT 2017
Resend with my member's email address.
Hi,
I'm trying to understand the optional size argument in file.readlines method. The help(file) shows:
| readlines(...) | readlines([size]) -> list of strings, each a line from the file. | | Call readline() repeatedly and return a list of the lines so read. | The optional size argument, if given, is an approximate bound on the | total number of bytes in the lines returned.
>From the documentation:f.readlines() returns a list containing all the lines of data in the file.
If given an optional parameter sizehint, it reads that many bytes from the file
and enough more to complete a line, and returns the lines from that.
This is often used to allow efficient reading of a large file by lines,
but without having to load the entire file in memory. Only complete lines
will be returned.
I wrote the function below to try it, thinking that it would print multiple times, 3 lines at a time, but it printed all in one shot, just like when I din't specify the optional argument. Could someone explain what I've missed? See input file and output below.
Thanks,Nancy
def readLinesWithSize(): # bufsize = 65536
bufsize = 45 with open('input.txt') as f: while True: # print len(f.readlines(bufsize)) # this will print 33 print lines = f.readlines(bufsize) print lines if not lines: break for line in lines: pass readLinesWithSize()
Output:
['1CSCO,100,18.04\n', '2ANTM,200,45.03\n', '3CSCO,150,19.05\n', '4MSFT,250,80.56\n', '5IBM,500,22.01\n', '6ANTM,250,44.23\n', '7GOOG,200,501.45\n', '8CSCO,175,19.56\n', '9MSFT,75,80.81\n', '10GOOG,300,502.65\n', '11IBM,150,25.01\n', '12CSCO1,100,18.04\n', '13ANTM1,200,45.03\n', '14CSCO1,150,19.05\n', '15MSFT1,250,80.56\n', '16IBM1,500,22.01\n', '17ANTM1,250,44.23\n', '18GOOG1,200,501.45\n', '19CSCO1,175,19.56\n', '20MSFT1,75,80.81\n', '21GOOG1,300,502.65\n', '22IBM1,150,25.01\n', '23CSCO2,100,18.04\n', '24ANTM2,200,45.03\n', '25CSCO2,150,19.05\n', '26MSFT2,250,80.56\n', '27IBM2,500,22.01\n', '28ANTM2,250,44.23\n', '29GOOG2,200,501.45\n', '30CSCO2,175,19.56\n', '31MSFT2,75,80.81\n', '32GOOG2,300,502.65\n', '33IBM2,150,25.01\n']
[]
The input file contains 33 lines of text, 15 or 16 letter each (15 - 16 bytes):1CSCO,100,18.042ANTM,200,45.033CSCO,150,19.054MSFT,250,80.565IBM,500,22.016ANTM,250,44.237GOOG,200,501.458CSCO,175,19.569MSFT,75,80.8110GOOG,300,502.6511IBM,150,25.0112CSCO1,100,18.0413ANTM1,200,45.0314CSCO1,150,19.0515MSFT1,250,80.5616IBM1,500,22.0117ANTM1,250,44.2318GOOG1,200,501.4519CSCO1,175,19.5620MSFT1,75,80.8121GOOG1,300,502.6522IBM1,150,25.0123CSCO2,100,18.0424ANTM2,200,45.0325CSCO2,150,19.0526MSFT2,250,80.5627IBM2,500,22.0128ANTM2,250,44.2329GOOG2,200,501.4530CSCO2,175,19.5631MSFT2,75,80.8132GOOG2,300,502.6533IBM2,150,25.0
More information about the Tutor
mailing list