user4290866
user4290866

Reputation:

Find out if file pointer is at EOF in Python

I am trying to find out whether my file pointer is at the EOF like in this example code: (EDITED)

f = open("test.dat")

someFunctionDoingStuffOn_f(f)

if f == EOF:         # to keep something like this would be important in my case
    print "EOF reached"
else:
    print "Not EOF"

But I do not know if there is anything like this available in Python.

I have edited the question by adding someFunctionDoingStuffOn_f(f), because it might be that I do not know what happened with f before hand. This excludes some approaches.

Upvotes: 3

Views: 6921

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

Based on martijns comment you can use the tell but I really don't see how it is going to make a difference:

import os

R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)

while R.f.tell() < n:
    line = R.f.readline()
    print(line)
    print("Not at EOF")
print("At EOF")

Where R.f is the file object from your class in the previous question but you cannot use tell in the same way using islice.

Or using it using if's to be more like the logic in your question:

import os

R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)

while True:
    if R.f.tell() != n:
        line = R.f.readline()
        print(line)
        print("Not at EOF")
    else:
         print("At EOF")
         break

Upvotes: 2

Joonazan
Joonazan

Reputation: 1416

This is something that usually should not be done. However it might be reasonable in your case. Please provide some context if my suggestions are not applicable.

1.

with open("test.dat", "r") as f:
    for line in f:
        do_something_with_line(line)

2.

with open("test.dat", "r") as f:
    whole_file = file.read()

After edit:

Take a look at https://docs.python.org/3.5/library/io.html. You might be able to use .read(maxbytes) to do what you want.

Upvotes: 0

Related Questions