[Tutor] making a function work with os.path.walk()
Christopher Spears
cspears2002 at yahoo.com
Fri Feb 13 19:05:31 EST 2004
I wrote a function called get_size(n,dir,files). This
is the code:
import os
def get_size(n,dir,files):
files_of_size = {}; sizes = [];
biggest_files = []; files_sizes = [];
files = map(os.path.join,[dir] * len(files),files)
files = filter(lambda x: not os.path.isdir(x)
and not os.path.islink(x),
os.listdir(dir))
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 function takes a number n and a directory name and
prints out the n largest files. However when I try to
use it with os.path.walk() I get the following result.
>>> os.path.walk('.',get_size,3)
[['Unit5.doc'], 22016L]
[['Unit8.doc'], 22528L]
[['Unit6.doc'], 23552L]
Traceback (most recent call last):
File "<pyshell#4>", 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 cannot decipher the error message. From what I can
gather, the function works fine in its current
directory, but seems to be having problems with the
other directory in the current directory. What I find
odd is that it claims that the .JPG doesn't exist, but
it is in the other directory. Suggestions, hints,
etc?
-Chris
More information about the Tutor
mailing list