fp = open("a.txt")
#do many things with fp
c = fp.read()
if c is None:
print 'fp is at the eof'
除了上面的方法,任何其他方式来找出是否是fp已经在eof?
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)
我真的不明白为什么python仍然没有这样的功能。我也不同意使用以下内容
f.tell() == os.fstat(f.fileno()).st_size
主要原因是f.tell()
不太适合某些特殊条件。
对我有用的方法如下。如果你有一些伪代码,如下所示
while not EOF(f):
line = f.readline()
" do something with line"
您可以将其替换为:
lines = iter(f.readlines())
while True:
try:
line = next(lines)
" do something with line"
except StopIteration:
break
此方法很简单,您无需更改大部分代码。
如果Python读取函数达到EOF,它们将返回一个空字符串
f = open(filename,'r')
f.seek(-1,2) # go to the file end.
eof = f.tell() # get the end of file location
f.seek(0,0) # go back to file beginning
while(f.tell() != eof):
<body>
您可以使用file methods seek()和tell()来确定文件末尾的位置。找到位置后,回头查看文件
你可以通过调用tell()
方法到达EOF
后使用readlines()
方法,如下所示:
fp=open('file_name','r')
lines=fp.readlines()
eof=fp.tell() # here we store the pointer
# indicating the end of the file in eof
fp.seek(0) # we bring the cursor at the begining of the file
if eof != fp.tell(): # we check if the cursor
do_something() # reaches the end of the file
获取文件的EOF位置:
def get_eof_position(file_handle):
original_position = file_handle.tell()
eof_position = file_handle.seek(0, 2)
file_handle.seek(original_position)
return eof_position
并将其与当前位置进行比较:get_eof_position == file_handle.tell()
。
虽然我个人会使用with
语句来处理打开和关闭文件,但是如果您必须从stdin读取并需要跟踪EOF异常,请执行以下操作:
使用EOFError
的try-catch作为例外:
try:
input_lines = ''
for line in sys.stdin.readlines():
input_lines += line
except EOFError as e:
print e
分批读取BATCH_SIZE
行文件(最后一批可以更短):
BATCH_SIZE = 1000 # lines
with open('/path/to/a/file') as fin:
eof = False
while eof is False:
# We use an iterator to check later if it was fully realized. This
# is a way to know if we reached the EOF.
# NOTE: file.tell() can't be used with iterators.
batch_range = iter(range(BATCH_SIZE))
acc = [line for (_, line) in zip(batch_range, fin)]
# DO SOMETHING WITH "acc"
# If we still have something to iterate, we have read the whole
# file.
if any(batch_range):
eof = True
Python没有内置的eof检测功能,但该功能有两种方式:如果没有更多的字节需要读取,f.read(1)
将返回b''
。这适用于文本和二进制文件。第二种方法是使用f.tell()
来查看当前的搜索位置是否在最后。如果您希望EOF测试不要更改当前文件位置,那么您需要一些额外的代码。
以下是两种实现方式。
使用tell()方法
import os
def is_eof(f):
cur = f.tell() # save current position
f.seek(0, os.SEEK_END)
end = f.tell() # find the size of file
f.seek(cur, os.SEEK_SET)
return cur == end
使用read()方法
def is_eof(f):
s = f.read(1)
if s != b'': # restore position
f.seek(-1, os.SEEK_CUR)
return s == b''
怎么用这个
while not is_eof(my_file):
val = my_file.read(10)
我用这个函数:
# Returns True if End-Of-File is reached
def EOF(f):
current_pos = f.tell()
file_size = os.fstat(f.fileno()).st_size
return current_pos >= file_size
您可以使用下面的代码片段逐行读取,直到文件结尾:
line = obj.readline()
while(line != ''):
# Do Something
line = obj.readline()
“for-else”设计经常被忽视。见:Python Docs "Control Flow in Loop":
例
with open('foobar.file', 'rb') as f:
for line in f:
foo()
else:
# No more lines to be read from file
bar()
我认为从文件中读取是确定它是否包含更多数据的最可靠方法。它可能是一个管道,或者另一个进程可能会将数据附加到文件等。
如果您知道这不是问题,您可以使用以下内容:
f.tell() == os.fstat(f.fileno()).st_size
在执行二进制I / O时,以下方法很有用:
while f.read(1):
f.seek(-1,1)
# whatever
优点是,有时您正在处理二进制流,并且事先并不知道您需要读多少。
您可以在调用fp.tell()
方法之前和之后比较read
的返回值。如果它们返回相同的值,则fp为eof。
此外,我认为您的示例代码实际上不起作用。据我所知,read
方法永远不会返回None
,但它确实在eof上返回一个空字符串。
因为python在EOF上返回空字符串,而不是“EOF”本身,你可以只检查它的代码,写在这里
f1 = open("sample.txt")
while True:
line = f1.readline()
print line
if ("" == line):
print "file finished"
break;
遇到EOF时,read返回空字符串。文件是here。
f=open(file_name)
for line in f:
print line
如果文件在非块模式下打开,返回的字节数少于预期并不意味着它在eof上,我会说@ NPE的答案是最可靠的方式:
f.tell()== os.fstat(f.fileno())。st_size