Ctrl-D is recognized not necessarily as EOF, but as "terminate current read()
call".
If you have an empty line (or just pressed Ctrl-D) and press Ctrl-D, your read()
terminates immediately and returns 0 read bytes. And this is a sign for EOF.
If you have data in a line and press Ctrl-D, your read()
terminates with whatever there has been typed, of course without a terminating newline ('\n'
).
So if you have input data, you press Ctrl-D twice of a non-empty line or once on a empty one, i.e. with Enter before.
This all holds for the normal OS interface, accessible from Python via os.read()
.
Python file objects, and also file iterators, treat the first EOF recognized as termination for the current read()
call, as they suppose there is nothing any longer. A next read()
call tries again and needs another Ctrl-D in order to really return 0 bytes. The reason is that a file object read()
always tries to return as many bytes as requested and tries to fill up if a OS read()
returns less than requested.
As opposite to file.readline()
, iter(file)
uses the internal read()
functions to read and thus always has this special requirement of the extra Ctrl-D.
I always use iter(file.readline, '')
to read line-wise from a file.