Skip to content
Advertisement

Get the size of a folder in Linux server

While the following code works well in windows, in Linux server (of pythonanywhere) the function only returns 0, without errors. What am I missing?

import os

def folder_size(path):
    total = 0
    for entry in os.scandir(path):
        if entry.is_file():
            total += entry.stat().st_size
        elif entry.is_dir():
            total += folder_size(entry.path)
    return total

print(folder_size("/media"))

Ref: Code from https://stackoverflow.com/a/37367965/6546440

Advertisement

Answer

The solution was given by @gilen-tomas in the comments:

import os

def folder_size(path):
    total = 0
    for entry in os.scandir(path):
        if entry.is_file():
            total += entry.stat().st_size
        elif entry.is_dir():
            total += folder_size(entry.path)
    return total

print(folder_size("/home/your-user/your-proyect/media/"))

A complete path is needed!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement