newbie: strange python problem

Alex Martelli aleaxit at yahoo.com
Thu Apr 10 08:54:00 EDT 2003


maxx wrote:

> Simple code (I think):
> 
> ---
> #!/usr/bin/python
> 
> import os
> 
> for line in os.popen('ls -la /').readlines():
>     direntry = line.split()
>     print direntry
>     print direntry[0]
>     print direntry[1]
>     print direntry[2]
> ---
> 
> No list-items with an index above 1 are printed. They produce a
> 'IndexError: list index out of range' error... which is strange, because
> the list 'direntry' is 9 items large, so listitems up to index 8 should be
> printed... right?
> 
> maxx

Not necessarily.  When I run it on my system, ls -la / produces
output that starts with a two-words line, such as
    
total 108

or the like.  So, running this script obviously does produce an
IndexError, and specifically:

bash-2.05b$ python pap.py
['total', '108']
total
108
Traceback (most recent call last):
  File "pap.py", line 10, in ?
    print direntry[2]
IndexError: list index out of range


Is this the symptom you're observing?  Apparently not, since you say
"the list 'direntry' is 9 items large", while in this case it's most
obviously only two...


Alex





More information about the Python-list mailing list