How do I tell the difference between the end of a text file, and an empty line in a text file?

Asun Friere afriere at yahoo.co.uk
Thu May 17 02:02:55 EDT 2007


On May 17, 7:47 am, walterbyrd <walterb... at iname.com> wrote:
> Python's lack of an EOF character is giving me a hard time.

The difference is simply that an empty line contains a '\n' while EOF
does not.  If you strip() your line before testing you will have
trouble.  But the minimal cases you post (properly indented and with
the missing ':' in place), should work (they just won't produce any
output). Repairing the first , I'm using dots (aka stops, periods) for
spaces here to stop the code getting munged :

line = fobj.readline()
while line :
....print line.strip()
....line = fobj.realine()

This does work look at this output (and note the empty lines):
line with stuff
line with more stuff

line after the empty line and before another

last line

In python it is more ideomatic to write this general kind of loop with
a break statement, thus:

while True :
....line = fobj.readline()
....if not line : break
....print line.strip()

However since file has for a long time been an iterable the easiest
and most readible way to write it is this:

for line in fobj :
....print line.strip()

Asun




More information about the Python-list mailing list