newbie: strange python problem

Skip Montanaro skip at pobox.com
Thu Apr 10 16:10:47 CEST 2003


    maxx> #!/usr/bin/python

    maxx> import os

    maxx> for line in os.popen('ls -la /').readlines():
    maxx>     direntry = line.split()
    maxx>     print direntry
    maxx>     print direntry[0]
    maxx>     print direntry[1]
    maxx>     print direntry[2]
    maxx> ---

    maxx> No list-items with an index above 1 are printed. They produce a
    maxx> 'IndexError: list index out of range' error... which is strange,
    maxx> because the list 'direntry' is 9 items large, so listitems up to
    maxx> index 8 should be printed... right?

Note that you are munch on the precise output of ls -la /, which includes
the summary line at the start of the listing, not just the directory entries
themselves.

Try os.listdir("/") instead:

    >>> print os.listdir("/")
    ['.DS_Store', '.hidden', '.Trashes', '.vol', 'Applications',
    'Applications (Mac OS 9)', 'automount', 'backup', 'bin', 'cores',
    'Desktop (Mac OS 9)', 'Desktop DB', 'Desktop DF', 'Desktop Folder',
    'dev', 'Developer', 'Documents', 'etc', 'include', 'Installer Log File',
    'Library', 'mach', 'mach.sym', 'mach_kernel', 'Network', 'private',
    'sbin', 'Shutdown Check', 'STV0680 Camera Snapshots', 'sw', 'System',
    'System Folder', 'Temporary Items', 'TheVolumeSettingsFolder', 'tmp',
    'Trash', 'Users', 'usr', 'var', 'Volumes'] 

That will only give you the names, but you can then call os.stat for each
entry to get the other information in the ls listing.

Skip





More information about the Python-list mailing list