win32: computing sizes of directories
Donald O'Donnell
donod at home.com
Fri Nov 10 21:58:29 EST 2000
Les,
Here's a little recursive function that should do the job
on any platform (Windows, Unix or Mac):
###################################################
import os, os.path
def dirSize(p):
"""Recursively compute the size of a given directory (p) by
adding up the sizes of its component files and sub directories.
"""
size = 0L # could go over 2 gigs, so better make it a long
names = os.listdir(p) # make a list of the names in the dir
for n in names: # for each name:
path = os.path.join(p, n) # make it a full path name
if os.path.isfile(path): # if it's a file:
size = size + os.path.getsize(path) # add it's size
elif os.path.isdir(path): # if it's a directory:
size = size + getSize(path) # recursive call
return size
###################################################
I've also got a printDirSize function/script which uses this
function and prints names and sizes of all files/directories in
a directory (nicely formatted like dir or ls command) to stdout,
and can also sort on name or size, ascending or descending.
Let me know if you can use it and I'll pass it along.
Cheers,
Don O'Donnell
Les Schaffer wrote:
>
> i was looking for a fast way to compute the size of a subdirectory in
> wondows (unix: 'du -s dirName' ) on specific directories in windows
> and i looked through the win32 extensions and couldnt find anything.
>
> but i am guessing its in there somewhere. anyone know?
>
> many thanks
>
> les schaffer
More information about the Python-list
mailing list