[Tutor] readlines code
Rick Pasotto
rick@niof.net
Mon Jun 30 21:56:04 2003
On Mon, Jun 30, 2003 at 09:43:37PM -0400, Cliff Martin wrote:
> Hi,
>
> I'm trying to read in an ASCII file of a fairly large set of data with
> data separated by spaces and each line ending with a linefeed. If I use
> readlines() I get all the data but each line still has a \n tacked on.
> If I use:
>
> f=open("c:/transfer/filename")
> for line in f.readlines():
> words=line.rstrip().split()
>
> I get only the last line of the file in words. Could someone explain
> why this is happening? There is something about the use of Python here
> that I'm not understanding. Thanks for any help.
I suspect you're only *doing* something to the last line.
Consider the following two programs:
f = open("c:/transfer/filename")
for line in f.readlines():
words=line.rstrip().split()
print words
f = open("c:/transfer/filename")
for line in f.readlines():
words=line.rstrip().split()
print words
Both process all the lines in the file but the first only prints out the
last line while the second prints out all the lines.
Indentation is *critical* in python.
--
"Damn all expurgated books; the dirtiest book of all is the expurgated book."
-- Walt Whitman
Rick Pasotto rick@niof.net http://www.niof.net