如何确定文件是否在其“eof”中?

时间:2012-04-13 11:52:09

标签: python file 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了?

21 个答案:

答案 0 :(得分:50)

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)

答案 1 :(得分:47)

“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()

答案 2 :(得分:30)

我认为从文件中读取是确定它是否包含更多数据的最可靠方法。它可能是一个管道,或者另一个进程可能会将数据附加到文件等。

如果您知道这不是问题,您可以使用以下内容:

f.tell() == os.fstat(f.fileno()).st_size

答案 3 :(得分:10)

执行二进制I / O时,以下方法很有用:

while f.read(1):
    f.seek(-1,1)
    # whatever

优势在于,有时您正在处理二进制流,并且事先并不知道您需要阅读多少。

答案 4 :(得分:8)

您可以在调用fp.tell()方法之前和之后比较read的返回值。如果它们返回相同的值,则fp为eof。

此外,我不认为您的示例代码确实有效。据我所知,read方法永远不会返回None,但它会在eof上返回一个空字符串。

答案 5 :(得分:8)

因为python在EOF上返回空字符串,而不是" EOF"本身,你可以检查它的代码,写在这里

f1 = open("sample.txt")

while True:
    line = f1.readline()
    print line
    if ("" == line):
        print "file finished"
        break;

答案 6 :(得分:7)

遇到EOF时,

read返回空字符串。文档为here

答案 7 :(得分:6)

f=open(file_name)
for line in f:
   print line

答案 8 :(得分:4)

如果文件在非块模式下打开,返回的字节数少于预期并不意味着它在eof上,我会说@ NPE的答案是最可靠的方式:

  

f.tell()== os.fstat(f.fileno())。st_size

答案 9 :(得分:3)

我真的不明白为什么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 :(得分:2)

这是使用Walrus运算符执行此操作的方法(Python 3.8中的新增功能)

f = open("a.txt", "r")

while (c := f.read(n)):
    process(c)

f.close()

有用的Python文档(3.8):

Walrus运算符:https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions

文件对象的方法:https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

答案 11 :(得分:2)

如果Python读取函数达到EOF

,它们将返回一个空字符串

答案 12 :(得分:1)

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 搜索() tell() 来确定文件结尾的位置。找到位置后,回头找回文件

答案 13 :(得分:1)

通过致电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

答案 14 :(得分:1)

获取文件的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()

答案 15 :(得分:0)

此代码适用于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]=="\n":
            EOF=k
        else:
            temp+=1
print("Given file has",EOF,"lines")
file.close()

答案 16 :(得分:0)

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)

Play with this code

答案 17 :(得分:0)

批量读取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

答案 18 :(得分:0)

虽然我个人会使用with语句来处理打开和关闭文件,但是如果您必须从stdin读取并需要跟踪EOF异常,请执行以下操作:

使用带有EOFError的try-catch作为例外:

try:
    input_lines = ''
    for line in sys.stdin.readlines():
        input_lines += line             
except EOFError as e:
    print e

答案 19 :(得分:-1)

我使用这个功能:

function missingLetterIs(str) {
  var prev = -1;
  for(var character of str) {
    var curr = character.codePointAt(0);
    if(prev >= 0 && curr - prev !== 1)
      return String.fromCodePoint(prev+1);
    prev = curr;
  }
}

答案 20 :(得分:-5)

您可以使用下面的代码段逐行读取,直到文件末尾:

line = obj.readline()
while(line != ''):
    # Do Something
    line = obj.readline()