Python 如何确定文件是否处于“eof”?
除了上述方法外,任何其他确定is fp是否已处于eof的方法?您可以在调用Python 如何确定文件是否处于“eof”?,python,file,eof,Python,File,Eof,除了上述方法外,任何其他确定is fp是否已处于eof的方法?您可以在调用read方法之前和之后比较fp.tell()的返回值。如果它们返回相同的值,则fp为eof 此外,我认为您的示例代码实际上不起作用。据我所知,read方法永远不会返回None,但它确实会在eof上返回一个空字符串。我认为从文件中读取是确定它是否包含更多数据的最可靠方法。它可能是一个管道,或者另一个进程可能正在将数据附加到文件等 如果您知道这不是问题,您可以使用以下方法: fp = open("a.txt") #do man
read
方法之前和之后比较fp.tell()
的返回值。如果它们返回相同的值,则fp为eof
此外,我认为您的示例代码实际上不起作用。据我所知,
read
方法永远不会返回None
,但它确实会在eof上返回一个空字符串。我认为从文件中读取是确定它是否包含更多数据的最可靠方法。它可能是一个管道,或者另一个进程可能正在将数据附加到文件等
如果您知道这不是问题,您可以使用以下方法:
fp = open("a.txt")
#do many things with fp
c = fp.read()
if c is None:
print 'fp is at the eof'
Python read函数在到达EOF时将返回一个空字符串。read()读取到文件末尾,因此在成功完成后,您知道文件处于EOF;没有必要检查。如果无法达到EOF,则会引发异常 当以块形式而不是使用
read()
读取文件时,当read
返回的字节数小于所请求的字节数时,您就知道遇到了EOF。在这种情况下,下面的read
调用将返回空字符串(而不是None
)。下面的循环以块的形式读取文件;它最多调用一次read
f.tell() == os.fstat(f.fileno()).st_size
或简称:
assert n > 0
while True:
chunk = fp.read(n)
if chunk == '':
break
process(chunk)
遇到EOF时,read返回空字符串。文档是。如果文件是在非块模式下打开的,返回的字节比预期的少并不意味着它处于eof,我认为@NPE的答案是最可靠的方式: f、 tell()==os.fstat(f.fileno()).st\u size “为他人”的设计常常被忽视。见: 示例
for chunk in iter(lambda: fp.read(n), ''):
process(chunk)
执行二进制I/O时,以下方法很有用:
with open('foobar.file', 'rb') as f:
for line in f:
foo()
else:
# No more lines to be read from file
bar()
优点是,有时您正在处理二进制流,并且事先不知道需要读取多少。您可以使用下面的代码段逐行读取,直到文件结束:
while f.read(1):
f.seek(-1,1)
# whatever
虽然我个人会使用
with
语句来处理打开和关闭文件的操作,但如果您必须从stdin读取数据并需要跟踪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>
使用带有eoferor
的try catch作为例外:
f=open(file_name)
for line in f:
print line
由于python在EOF上返回空字符串,而不是“EOF”本身,因此您只需检查此处编写的代码即可
try:
input_lines = ''
for line in sys.stdin.readlines():
input_lines += line
except EOFError as e:
print e
我使用此功能:
f1 = open("sample.txt")
while True:
line = f1.readline()
print line
if ("" == line):
print "file finished"
break;
f=open(文件名'r')
f、 查找(-1,2)#转到文件末尾。
eof=f.tell()#获取文件结尾位置
f、 查找(0,0)#返回文件开头
而(f.tell()!=eof):
您可以使用seek()和tell()来确定文件结尾的位置。找到位置后,返回文件开头您可以通过调用readlines()
在到达EOF
后使用tell()
方法
方法,如下所示:
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>
我真的不明白为什么python仍然没有这样一个函数。我也不同意使用以下内容
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
f.tell() == os.fstat(f.fileno()).st_size
主要原因是f。tell()
在某些特殊情况下不太可能工作
我的方法如下所示。如果您有以下伪代码
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
f.tell() == os.fstat(f.fileno()).st_size
您可以将其替换为:
while not EOF(f):
line = f.readline()
" do something with line"
此方法很简单,您不需要更改大部分代码。以批大小
行的批读取文件(最后一批可以更短):
获取文件的EOF位置:
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
并将其与当前位置进行比较:get\u eof\u position==file\u handle.tell()
Python没有内置的eof检测功能,但该功能有两种可用方式:f.read(1)
如果没有更多字节可读取,将返回b'
。这适用于文本和二进制文件。第二种方法是使用f.tell()
查看当前搜索位置是否在末尾。如果您希望EOF测试不改变当前文件位置,那么您需要一些额外的代码
下面是两种实现
使用tell()方法
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
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 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
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
如何使用此功能
def is_eof(f):
s = f.read(1)
if s != b'': # restore position
f.seek(-1, os.SEEK_CUR)
return s == b''
.下面是一种使用Walrus操作符(Python 3.8中新增)执行此操作的方法
f=open(“a.txt”、“r”)
而(c:=f.read(n)):
过程(c)
f、 关闭()
有用的Python文档(3.8):
海象操作员:
文件对象的方法:此代码适用于python 3及更高版本
while not is_eof(my_file):
val = my_file.read(10)
同意,如果调用read()并处于EOF,它将返回'
我更喜欢fh.seek(0,2);文件大小=fh.tell();fh.seek(0)
事先,然后fh.tell()==文件大小
。按你的方式做有什么好处吗?注意:我当然建议将大小缓存到一个变量,不要在每个循环中调用os.fstat
。注意,如果文件以文本模式打开,这将不起作用:f.tell()
以字符为单位提供文件位置,os.fstat(f.fileno())。st_size
以字节为单位提供文件长度@布鲁诺布罗诺斯基的方法会奏效的。是的,你是对的。因此,没有有效的方法来检查是否达到了eof
?@Alcott:对于普通文件,有aix的方法。在分块阅读时,比如说使用fp.read(n)
,当返回的字符数小于n
时,你就会知道你点击了EOF。除非你有理由分块处理文件,否则逐行处理通常更自然,python提供的文件都是迭代器-因此您可以对文件中的行执行:…
并让for循环为您处理它。根据:“对于交互式原始流(tty/terminal),简短的结果并不意味着EOF即将发生。”@larsmans刚刚使用了这个,谢谢!虽然我的是针对二进制流的,但我应该注意到,如果chunk=='':
只适用于