[SOLVED] Python: Recursion and Generators

Status
You're currently viewing only tuffy's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

tuffy

Ars Scholae Palatinae
972
Is there a reason you're not using the os.walk function?

It sounds like it'll be easier to split this problem into two parts, one for recursively finding the size of a given root directory and another for finding all the subdirectories of a given root. Putting them both together should then give you the sizes you're looking for - assuming I understand the problem correctly.
 

tuffy

Ars Scholae Palatinae
972
If it's an optimization problem, then perhaps try forgoing the generator entirely and pass in an object for size accumulation, like:
Code:
def dir_sizes(basedir, accumulator):
    size = 4096

    for f in [os.path.join(basedir, l) for l in os.listdir(basedir)]:
        if (os.path.isfile(f)):
            size += os.path.getsize(f)
        elif (os.path.isdir(f)):
            size += dir_sizes(f, accumulator)
        else:
            #handle other types here
            pass

    accumulator.append((basedir, size))
    return size
Then just tweak the accumulation step to keep only the top N entries or something like that.
 
Status
You're currently viewing only tuffy's posts. Click here to go back to viewing the entire thread.
Not open for further replies.