Reputation: 331
Recently I am learning python, then I realize there exist a read1() in the python documentation. I am wondering what's the difference between read() and read1()? What the situation we should use read1() instead of read()?
https://docs.python.org/3/library/io.html#io.BufferedReader
Upvotes: 19
Views: 9762
Reputation: 1902
In short, read([size])
ensures it reads size
bytes (or until EOF
) and it may involve multiple reads on the underlying IO object if necessary.
read1([size])
is to get any data (at-most size
bytes) that is available in the buffer. If no data in buffer then do at-most 1 read()
to the IO object.
To elaborate:
read([size]):
if size
is negative or None, calls the underlying raw stream's readall()
method which would read until the EOF
is reached or it's going to block in a non-blocking mode. The underlying raw stream is duck-typed, meaning if it does not have a readall()
, then multiple calls to raw stream's read()
is made until EOF
is reached or it would block.
if the size
is a positive, read()
would return the available data from the buffer. If the available data is less than the size
, then multiple read()
calls are made to the raw stream until size
bytes are available or EOF is reached.
read1([size])
on the other hand returns any data that is available on the buffer even if it less than size
, If no data is available and size
is > 0, then it makes at most one read()
call to the underlying IO object.
if size
is omitted or < 0, then the size
of available buffer is used, So no read()
call performed on the raw stream in this case.
Upvotes: 18