Help With EOF character: URGENT

Greg Ewing (using news.cis.dfn.de) wmwd2zz02 at sneakemail.com
Mon Feb 23 03:42:10 CET 2004


dont bother wrote:
> Hi Buddies,
> I am facing this problem and I dont know what to use
> as EOF in python:

There's no "EOF character" in Python. When the end of a file is
reached, reading from it returns an empty string. To process
a file one character at a time, you can do

   while 1:
     c = f.read(1)
     if not c:
       break
     # process c here

In your case you seem to be dealing with words, so you can
take advantage of two Python features: (1) You can read
a line at a time with the readline() method. (2) You can
split a string into words with the split() method of strings.

   while 1:
     line = f.readline()
     if not line:
       break
     words = line.split()
     for word in words:
       # process word here

If you have a recent enough Python (>= 2.2 I think), you can
also iterate directly over the file, which will iterate over
its lines, so the above reduces to just

   for line in f:
     words = line.split()
     for word in words:
       # process word here

Note: The readline() method, and also "for line in f", returns
lines including the newline character on the end. That doesn't
matter here, because line.split() gets rid of all the whitespace,
but you need to be aware of it if you do other things with
the line. You can use

   line = line.strip()

to remove the newline if you need to.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list