Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 960
Rashomon Avatar asked Nov 28 '16 08:11

Rashomon


3 Answers

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!

like image 173
Rashomon Avatar answered Nov 16 '22 13:11

Rashomon


Depending on the filesystem, the underlying struct dirent may not know if any given entry is a file or directory (or something else). Perhaps, on the filesystem used by pythonanywhere, you need to stat first (stat_result.st_type ought to be valid).

Edit: A look in discussion on os.scandir suggests the DT_UNKNOWN case is handled by doing another stat. I'd still try confirming those checks work as expected.

like image 1
Yann Vernier Avatar answered Nov 16 '22 14:11

Yann Vernier


you can try this..

For linux :

import os
path = '/home/user/Downloads'
folder = sum([sum(map(lambda fname: os.path.getsize(os.path.join(directory, fname)), files)) for directory, folders, files in os.walk(path)])
MB=1024*1024.0
print  "%.2f MB"%(folder/MB)

For windows :

import win32com.client as com
folderPath = r"/home/user/Downloads"
fso = com.Dispatch("Scripting.FileSystemObject")
folder = fso.GetFolder(folderPath)
MB=1024*1024.0
print  "%.2f MB"%(folder.Size/MB)
like image 1
Shivkumar kondi Avatar answered Nov 16 '22 15:11

Shivkumar kondi