[Tutor] Why different behaviours?
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 26 Oct 2001 08:59:19 -0700 (PDT)
On Fri, 26 Oct 2001, Danny Kohn wrote:
> Why does:
> import string, sys
> f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt', 'r')
> line = f.readline()
> print line
>
> and:
>
> import string, sys
> f=open('d:/Dokument/Programprojekt/pythonworks/projects/H2/Lexicon.txt', 'r')
> for line in f.readline():
> print line
The variable naming in your second version might be obscuring an issue:
> for line in f.readline():
> print line
In this case, we're asking Python to do a for loop along every thing in an
f.readline(). In that case, we're going to go along every character of
that read line, so the loop might be better written as:
##
for character in f.readline():
print line
###
Also, Python's "print" statement will automatically put a newline, unless
we place a trailing comma. We can see this from this interpreter session:
###
>>> print "abc"
abc
>>> for letter in "abc":
... print letter
...
a
b
c
>>> for letter in "abc":
... print letter,
...
a b c
###
It sounds like you've had some programming experience already, so I don't
have qualms about recommending the official Python library:
http://www.python.org/doc/current/tut/tut.html
The section on "Fancier Output Formatting" should give you more control
over how your programs print things.
> 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?
According to:
http://www.python.org/doc/current/tut/node9.html#SECTION009200000000000000000
"""f.readline() reads a single line from the file; a newline character
(\n) is left at the end of the string, and is only omitted on the last
line of the file if the file doesn't end in a newline. This makes the
return value unambiguous; if f.readline() returns an empty string, the end
of the file has been reached, while a blank line is represented by '\n', a
string containing only a single newline."""
If you have more questions, please feel free to ask. Good luck!