[Tutor] Why different behaviours?

Blake Winton bwinton@tor.dhs.org
Fri, 26 Oct 2001 10:04:40 -0400


> Why does:
> import string, sys
> f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon
> .txt', 'r')
> line = f.readline()
> print line

This reads the first line, and prints it.

> import string, sys
> f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon
> .txt', 'r')
> for line in f.readline():
> 	print line

This reads the first line, sets the "line" variable to each character
in turn, and prints each of them.

> Also, what would be the way to read line after line until end of 
> file. How to detect end of file when reading a sequential file this way?

Your second example is close, but you need to use f.readlines()
instead of f.readline().  And the end of the file will end the for loop,
so you don't have to worry about it.

Later,
Blake.