如何确定文件是否到达“eof”?
- 2025-03-19 08:56:00
- admin 原创
- 48
问题描述:
fp = open("a.txt")
#do many things with fp
c = fp.read()
if c is None:
print 'fp is at the eof'
除了上述方法之外,还有其他方法可以确定 fp 是否已经到达 eof?
解决方案 1:
fp.read()
读取到文件末尾,因此成功完成后您就知道文件已到达 EOF;无需检查。如果无法到达 EOF,则会引发异常。
当以块的形式而不是使用 读取文件时,如果返回的字节数少于您请求的字节数,read()
您就知道您已经到达了 EOF 。在这种情况下,以下调用将返回空字符串(而不是)。以下循环以块的形式读取文件;它最多会调用一次。read
`readNone
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)
解决方案 2:
“for-else” 设计经常被忽视。请参阅:Python 文档“循环中的控制流”:
例子
with open('foobar.file', 'rb') as f:
for line in f:
foo()
else:
# No more lines to be read from file
bar()
解决方案 3:
我认为从文件中读取是确定文件是否包含更多数据的最可靠方法。它可能是一个管道,或者另一个进程可能正在将数据附加到文件等。
如果您知道这不是问题,则可以使用类似以下方法:
f.tell() == os.fstat(f.fileno()).st_size
解决方案 4:
由于 python 在 EOF 上返回空字符串,而不是“EOF”本身,因此您可以检查此处写的代码
f1 = open("sample.txt")
while True:
line = f1.readline()
print line
if ("" == line):
print "file finished"
break;
解决方案 5:
进行二进制 I/O 时,以下方法很有用:
while f.read(1):
f.seek(-1,1)
# whatever
优点是有时您正在处理二进制流并且事先不知道需要读取多少内容。
解决方案 6:
以下是使用 Walrus Operator(Python 3.8 中的新功能)执行此操作的一种方法
f = open("a.txt", "r")
while (c := f.read(n)):
process(c)
f.close()
有用的 Python 文档(3.8):
海象运算符:https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions
文件对象的方法:https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
解决方案 7:
fp.tell()
可以比较调用方法前后的返回值read
,如果返回值相同,则表示 fp 位于 eof。
此外,我认为您的示例代码实际上不起作用。read
据我所知,该方法永远不会返回None
,但它会在 eof 时返回一个空字符串。
解决方案 8:
f=open(file_name)
for line in f:
print line
解决方案 9:
我真的不明白为什么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
这种方法很简单,您不需要更改大部分代码。
解决方案 10:
当遇到 EOF 时,read 返回一个空字符串。文档在这里。
解决方案 11:
如果文件以非块模式打开,返回的字节数少于预期并不意味着它处于 eof,我会说@NPE 的答案是最可靠的方法:
f.tell() == os.fstat(f.fileno()).st_size
解决方案 12:
Python 没有内置的 eof 检测函数,但该功能有两种方式可用:如果没有更多字节可读取,f.read(1)
则返回。这适用于文本和二进制文件。第二种方法是用来查看当前查找位置是否在末尾。如果您希望 EOF 测试不改变当前文件位置,那么您需要一些额外的代码。b''
`f.tell()`
以下是两种实现。
使用 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)
玩一下这个代码。
解决方案 13:
如果 Python 读取函数到达 EOF,将返回一个空字符串
解决方案 14:
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>
您可以使用文件方法 seek()和tell()来确定文件末尾的位置。找到位置后,返回文件开头
解决方案 15:
您可以在到达后通过调用方法来使用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
解决方案 16:
分批读取文件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
解决方案 17:
获取文件的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()
。
解决方案 18:
我必须检查一个大的csv 文件来检测错误的编码字符,并使用逐行方法保持内存消耗“较低”。
with open(path, 'rb') as fd:
line = fd.readline()
while line.endswith(b'
'):
line = fd.readline()
# do some line processing
else:
print("fd is at the EOF")
对于非二进制模式,打开文件时无需b
删除字符串前缀b
。
-blockelse
不是必需的,但它只是为了强调循环顺利完成。
解决方案 19:
虽然我个人会使用with
语句来处理打开和关闭文件,但是在您必须从 stdin 读取并需要跟踪 EOF 异常的情况下,请执行以下操作:
使用 try-catch 作为EOFError
异常:
try:
input_lines = ''
for line in sys.stdin.readlines():
input_lines += line
except EOFError as e:
print e
解决方案 20:
我使用这个功能:
# 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
解决方案 21:
此代码适用于 Python 3 及以上版本
file=open("filename.txt")
f=file.readlines() #reads all lines from the file
EOF=-1 #represents end of file
temp=0
for k in range(len(f)-1,-1,-1):
if temp==0:
if f[k]=="
":
EOF=k
else:
temp+=1
print("Given file has",EOF,"lines")
file.close()
解决方案 22:
你可以尝试这个代码:
import sys
sys.stdin = open('input.txt', 'r') # set std input to 'input.txt'
count_lines = 0
while True:
try:
v = input() # if EOF, it will raise an error
count_lines += 1
except EOFError:
print('EOF', count_lines) # print numbers of lines in file
break
解决方案 23:
您可以使用下面的代码片段逐行读取,直到文件末尾:
line = obj.readline()
while(line != ''):
# Do Something
line = obj.readline()
扫码咨询,免费领取项目管理大礼包!