17

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

Shee Xiong Chen
  • 311
  • 2
  • 6
  • 2
    I think this question is on topic. https://meta.stackoverflow.com/a/273111/5267751 – user202729 Aug 30 '19 at 12:37
  • On this answer https://stackoverflow.com/a/37222446/6282820 the read1 is used, the guy says "Note that we use file.read1. file.read blocks until it gets all the bytes requested of it or EOF. file.read1 allows us to avoid blocking, and it can return more quickly because of this. No other answers mention this as well." Reading the documentation I could not tell the difference as well – Rodrigo Torres Aug 30 '19 at 12:57

1 Answers1

15

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.

Sam Daniel
  • 1,800
  • 12
  • 22