What is a Pythonic way to detect that the next read will produce an EOF in Python 3 (and Python 2)

Viewed 158

Currently, I am using

def eofapproached(f):
    pos  = f.tell()
    near = f.read(1) == ''
    f.seek(pos)
    return near

to detect if a file open in 'r' mode (the default) is "at EOF" in the sense that the next read would produce the EOF condition.

I might use it like so:

f = open('filename.ext') # default 'r' mode

print(eofapproached(f))

FYI, I am working with some existing code that stops when EOF occurs, and I want my code to do some action just before that happens.

I am also interested in any suggestions for a better (e.g., more concise) function name. I thought of eofnear, but that does not necessarily convey as specific a meaning.

Currently, I use Python 3, but I may be forced to use Python 2 (part of a legacy system) in the future.

2 Answers
Related