file.read()上的Python文档说明An empty string is returned when EOF is encountered immediately.文档进一步指出:
请注意,此方法可能会多次调用基础C函数fread(),以尽可能接近大小字节.另请注意,在非阻塞模式下,即使未给出大小参数,也可能返回的数据少于请求的数据.
我相信Guido已经提出了不添加f.eof()PERFECTLY CLEAR的观点,所以需要使用Python方式!
然而,我不清楚的是,如果你是一个确定的测试,如果你从读取中得到的字节数少于所要求的字节,那么你已经达到了EOF,但你确实得到了一些.
即:
with open(filename,'rb') as f:
while True:
s=f.read(size)
l=len(s)
if l==0:
break # it is clear that this is EOF...
if l<size:
break # ? Is receiving less than the request EOF???
Run Code Online (Sandbox Code Playgroud)
break如果您收到的呼叫数少于呼叫中请求的字节数,那么这是一个潜在的错误file.read(size)吗?