Newbie question about file input

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Aug 18 15:18:26 EDT 2004


In <cfvtf9$sku$1 at mozo.cc.purdue.edu>, Aaron Deskins wrote:

> Perhaps I should have been more specific. What does python store when 
> you read a blank line? Nothing? A null variable? A '\n'?

It reads '\n' as that's, more or less, the content in the text file for
that line.  In the file there may be some other platform specific byte
(combination) to denote a line ending.

> How about this:
> 
> import string
> import sys
> zf=open(sys.argv[1],'r')
> it = 0
> while 1:
>      line = zf.readline()
>      print line
>      rs = line.split()
>      print rs
>      if rs[0]== '[Event':
>          it+=1
>          print it
>      if not line:
>          break
> zf.close()
> 
> This fails when it tries the "if rs[0]== '[Event':" statement. rs[0] 
> doesn't exist (or is blank?) for a blank line in my input file.

Let's fire up the interpreter and see why:

  >>> line = "\n"
  >>> line
  '\n'
  >>> rs = line.split()
  >>> rs
  []
  >>> rs[0]
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  IndexError: list index out of range

A line without anything but whitespace characters "splits" to an empty
list.

> Another code:
> 
> import string
> import sys
> zf=open(sys.argv[1],'r')
> it = 0
> while 1:
>      line = zf.readline()
>      it+=1
>      if not line:
>          break
> zf.close()
> print it
> 
> This only ends when the end of file is reached. Why not when a blank 
> line is read? How does python treat the variable line (after a readline) 
> differently after a blank line or the last line of the file?

As said before: a blank line is not really empty but contains a newline
character. When the file ends, readline() returns an empty string.

Ciao,
	Marc 'BlackJack' Rintsch




More information about the Python-list mailing list