Monday, July 6, 2020

Python end of file Detection Method

Python doesn't have built-in eof detection function but that functionality is available in two ways: f.read(1) will return b'' if there are no more bytes to read. This works for text as well as binary files. The second way is to use f.tell() to see if current seek position is at the end. If you want EOF testing not to change the current file position then you need bit of extra code.

Below are both implementations.

Using tell() method

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

Using read() method

def is_eof(f):
  s = f.read(1)
  if s != b'':    # restore position
  f.seek(-1, os.SEEK_CUR)
  return s == b''
#another Simple Method for End of file Detection 
f1 = open("sample.txt")

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