pythonscandir

Measure directory size with Python


I am new to Python and I need to get the size from a directory with more than 500k files. I found some code on the internet which should be really fast. Somehow it doesnt work and I dont know why. The current output is only 'Test' so it doesnt even enter the function.

import time
import os

start_time = time.time()
print('Test')
def getSize(path):
    print('Test2')
    total = 0
    for entry in os.scandir(path):
        if entry.is_dir(follow_symlinks=False):
            total += getSize(entry.path)
        else:
            total += entry.stat(follow_symlinks=False).st_size
    return total

    print (float(getSize('U:\Java'))/1024/1024/1024)
    print("--- %s Sekunden ---" % round(time.time() - start_time, 2))

Additional question: Is there an even faster way to search such big directories with python or other languages?


Solution

  • The two last lines in your program, where you call the function, are indented and therefore considered a part of the function and will not execute. Simply dedent them.