[Tutor] EOF function

Lloyd Kvam pythontutor@venix.com
Fri Jul 4 11:01:02 2003


I suspect you are writing in Python, but thinking in C.  However, I'll
try to help.

There is no escape sequence for EOF.  Very old MS-DOS used a <control-z> (chr(26))
character to mark the end of a file.  The normal process is that the OS knows
how many bytes are in a file.  Trying to read more than that means you have
reached the EOF.

The Python file object includes methods:
	tell
	seek
tell reports the current position, an offset in bytes from the start of the file.
seek allows you to set the position within the file using an offset and
specifying if that offset is relative to the start, current position, or end
of the file.

You can use the os and stat modules to find the size of a file.

<unchecked/untested code.  should be close>
import os, stat
file_size = os.stat(file_path_name)[stat.ST_SIZE]
myfile = file(file_path_name,'rb')
mydata = myfile.read(1000)
if myfile.tell() < file_size:
	print "more data"
else:
	print "reached end"

os.stat returns a tuple.  The stat module provides constants for decoding
the tuple.

For more detail see the module documentation.

Now the file objects read methods will return '' when there is no more data
to be read.  I would expect that it is easier to read and get a '' than it
is to constantly check the file position before reading.

Silviu Cojocaru wrote:
> I want to write a function that will return 1 if EndOfFile is reached 
> and 0 if not. Problem is I have no idea how that's done. Maybe there is 
> a function that could return the current position in a file and if the 
> char at that position is the EOF char then return 1.
> 
> Problems:
> I do not know the escape sequence for EOF
> I do not know a function that returns the current position in a file so 
> maybe I need to write it as well :/ and again I would be at a loss.
> 
> If anyone can help me, I would be grateful.
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582