Get folder size on Linux server

While the following code works well on Windows, on a Linux server (from pythonanywhere), the function 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"))

Link: Code from https://stackoverflow.com/a/312960/

+4
source share
5 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/"))

It takes a full path!

0
source

This worked for me on linux (Ubuntu 16.04 server, python 3.5), but there may be some permission errors if the process does not have permission to read the file.

+1
source

struct dirent , - ( - ). , , pythonanywhere, stat (stat_result.st_type ).

: os.scandir , DT_UNKNOWN . , , .

+1

.

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)

:

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)
+1

, - cmd python:

import subprocess
import re

cmd = ["du", "-sh", "-b", "media"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
tmp = str(proc.stdout.read())
tmp = re.findall('\d+', tmp)[0]

print(tmp)

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

0

Source: https://habr.com/ru/post/1662111/


All Articles