[Tutor] OSError

Kent Johnson kent37 at tds.net
Wed Mar 15 12:00:49 CET 2006


Christopher Spears wrote:
> I am trying to write a function that takes a directory
> name and describes the contents of the directory (file
> name and size) recursively.  Here is what I have
> written so far:
> 
> import os, os.path
> 
> def describeDirectory(directory):
>     if os.listdir(directory) == []:
>         print "Empty directory!"
>     else:
>         for files in os.listdir(directory):
>             if os.path.isdir(files):
>                 print files, ' is a directory!'
>             else:
>                 print files, 'SIZE: ',
> os.path.getsize(files)
> 
> print 'Current Directory: \n'
> describeDirectory('.')
> print '\n'
> print './testFiles: \n'
> describeDirectory('./testFiles')

Chris,

os.path.getsize() needs the full path or relative path to the file, but 
os.listdir() just returns the bare file name, so there is a slight 
mismatch here. describeDirectory() works for the current dir because the 
bare file name is the correct relative path. You should use 
os.path.join(directory, files) to create the full path to pass to 
os.path.getsize().

BTW 'files' is not such a great name because it is just one file, not 
multiple. But don't change it to 'file', that is the name of a built-in 
function! Maybe 'f' or 'name' or 'filename'.

Kent



More information about the Tutor mailing list