如何确定文件是否处于其“eof"? [英] How to find out whether a file is at its `eof`?
问题描述
fp = open("a.txt")
#do many things with fp
c = fp.read()
if c is None:
print 'fp is at the eof'
除了上面的方法,还有什么方法可以判断fp是否已经在eof了吗?
Besides the above method, any other way to find out whether is fp is already at the eof?
推荐答案
fp.read()
读到文件末尾,所以在它成功完成后你知道文件处于 EOF;没有必要检查.如果它无法到达 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.
当以块的形式读取文件而不是使用 read()
时,当 read
返回的字节数少于您请求的字节数时,您就知道您已达到 EOF.在这种情况下,下面的 read
调用将返回空字符串(不是 None
).以下循环分块读取文件;它最多会调用 read
一次.
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)
或者,更短:
for chunk in iter(lambda: fp.read(n), ''):
process(chunk)
这篇关于如何确定文件是否处于其“eof"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!