[Tutor] losing info

Christopher Spears cspears2002 at yahoo.com
Sat Feb 14 18:10:25 EST 2004


I have run up against a brick wall! I wrote a function
called get_size(n,directory,files):

import os

def get_size(n,directory,files):
files_of_size = {}; sizes = [];
biggest_files = [];

files = filter(lambda x: not os.path.isdir(x)
and not os.path.islink(x), files)

for f in files:
files_of_size.setdefault(os.path.getsize(f),[]).append(f)

sizes = files_of_size.keys()
sizes.sort(); sizes.reverse();
for s in sizes:
biggest_files.append([files_of_size[s],s])

while n > 0:
print biggest_files[n-1]
n = n - 1

The hard part is getting it to work with os.path.walk.
This happens:

os.path.walk('.',get_size,3)
[['Unit5.doc'], 22016L]
[['Unit8.doc'], 22528L]
[['Unit6.doc'], 23552L]

Traceback (most recent call last):
File "", line 1, in -toplevel-
os.path.walk('.',get_size,3)
File "C:\Python23\lib\ntpath.py", line 333, in walk
walk(name, func, arg)
File "C:\Python23\lib\ntpath.py", line 327, in walk
func(arg, top, names)
File "C:\Documents and Settings\Christstopher
Spears\My Documents\python\unit9.question1c.py", line
11, in get_size
files_of_size.setdefault(os.path.getsize(f),[]).append(f)
File "C:\Python23\lib\ntpath.py", line 228, in getsize
return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory:
'DSCN4432.JPG'

I've been debugging the function, and this is what I
have found. The portion of the script that puts
together a list of file names works for both the
current directory and the directory underneath it.
However, the part of the function that is supposed to
assemble a dictionary of sizes and filenames is not
working for the directory underneath the current
directory. Somehow the list of filenames is getting
lost! Hence the file DSCN4432.JPG cannot be found! 
What could be causing this?

-Chris





More information about the Tutor mailing list