1. Describing a directory. There are several solutions to this exercise, naturally. One simple solution is:

    import os, sys, stat
    
    def describedir(start):
        def describedir_helper(arg, dirname, files):
            """ Helper function for describing directories """
            print "Directory %s has files:" % dirname
            for file in files:
                # find the full path to the file (directory + filename)
                fullname = os.path.join(dirname, file)
                if os.path.isdir(fullname):
                    # if it's a directory, say so; no need to find the size
                    print '  '+ file + ' (subdir)' 
                else: 
                    # find out the size, and print the info.
                    size = os.stat(fullname)[stat.ST_SIZE]
                    print '  '+file+' size='  + `size`
    
        # Start the 'walk'.
        os.path.walk(start, describedir_helper, None)

    which uses the walk function in the os.path module, and works just fine:

    >>> import describedir
    >>> describedir.describedir2('testdir')
    Directory testdir has files:
      describedir.py size=939
      subdir1 (subdir)
      subdir2 (subdir)
    Directory testdir\subdir1 has files:
      makezeros.py size=125
      subdir3 (subdir)
    Directory testdir\subdir1\subdir3 has files:
    Directory testdir\subdir2 has files:

    Note that you could have found the size of the files by doing len(open(fullname, 'rb').read()), but this works only when you have read access to all the files and is quite inefficient. The stat call in the os module gives out all kinds of useful information in a tuple, and the stat module defines some names that make it unnecessary to remember the order of the elements in that tuple. See the Library Reference ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.