fp = open("a.txt")
#do many things with fp
c = fp.read()
if c is None:
print 'fp is at the eof'
除了上面的方法之外,还有没有其他方法来确定fp是否已经在eof?
发布于 2012-04-13 19:55:05
fp.read()
一直读到文件的末尾,所以在它成功完成之后,您就知道文件是EOF的;不需要检查。如果它不能到达EOF,它将引发一个异常。
当按块而不是使用read()
读取文件时,当read
返回的字节数少于请求的字节数时,您就知道命中了EOF。在这种情况下,下面的read
调用将返回空字符串(不是None
)。下面的循环以块为单位读取文件;它最多只能调用一次read
。
assert n > 0
while True:
chunk = fp.read(n)
if chunk == '':
break
process(chunk)
或者,简称:
for chunk in iter(lambda: fp.read(n), ''):
process(chunk)
发布于 2016-06-16 17:51:09
因为python在EOF上返回空字符串,而不是"EOF“本身,所以您可以检查它的代码,编写在这里
f1 = open("sample.txt")
while True:
line = f1.readline()
print line
if ("" == line):
print "file finished"
break;
发布于 2014-08-01 09:39:13
执行二进制I/O时,以下方法非常有用:
while f.read(1):
f.seek(-1,1)
# whatever
这样做的好处是,有时您正在处理二进制流,而事先并不知道需要读取多少内容。
https://stackoverflow.com/questions/10140281
复制相似问题