如何找出一个文件是否在它的“eof”? [英] How to find out whether a file is at its `eof`?
问题描述
$如果c是None:
print'fp在eof'
除了上述方法,任何其他方式来确定是否fp已经在eof?
fp.read ()
读取文件的最后,所以成功完成后,你知道文件是EOF;没有必要检查。如果无法达到EOF,它将引发异常。
以块为单位读取文件而不是 read()
,你知道当读取
返回的请求少于您要求的字节数时,您已经击中了EOF。在这种情况下,以下读取
调用将返回空字符串(而不是无
)。以下循环以块为单位读取文件;它将调用读取
最多一次太多。
断言n> ; 0
while True:
chunk = fp.read(n)
如果chunk =='':
break
进程(chunk)
或者更短:
对于块中的块(lambda:fp.read(n),''):
process(chunk)
fp = open("a.txt")
#do many things with fp
c = fp.read()
if c is None:
print 'fp is at the eof'
Besides the above method, any other way to find out whether is fp is already at the eof?
fp.read()
reads up to the end of the file, so after it's successfully finished you know the file is at EOF; there's no need to check. If it cannot reach EOF it will raise an exception.
When reading a file in chunks rather than with read()
, you know you've hit EOF when read
returns less than the number of bytes you requested. In that case, the following read
call will return the empty string (not None
). The following loop reads a file in chunks; it will call read
at most once too many.
assert n > 0
while True:
chunk = fp.read(n)
if chunk == '':
break
process(chunk)
Or, shorter:
for chunk in iter(lambda: fp.read(n), ''):
process(chunk)
这篇关于如何找出一个文件是否在它的“eof”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!