Answer the question
In order to leave comments, you need to log in
How to find out the size of a directory using Python?
In niks, there is a great command du, in order to immediately show the size of subdirectories in a directory.
How can I do this with a Python script?
I do it like this:
import os
#Π£ΠΊΠ°Π·ΡΠ²Π°Ρ Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΡ
basedir = "/home/user/test/"
#ΠΠΎΠΊΠ° ΠΏΡΠΈΠΌΠ΅ΠΌ ΡΡΠΎ ΡΠ°Π·ΠΌΠ΅Ρ ΠΏΠΎΠ΄Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΠΉ ΡΠ°Π²Π΅Π½ 0
sub_size = 0
#Π’Π°ΠΊ ΠΊΠ°ΠΊ ΠΌΡ Π½Π΅ Π·Π½Π°Π΅ΠΌ ΡΠΊΠΎΠ»ΡΠΊΠΎ ΠΏΠΎΠ΄Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΠΉ Π² Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΠΈ, ΠΏΠΎΠ»ΡΡΠ°Π΅ΠΌ ΠΈΡ
Π½Π°Π·Π²Π°Π½ΠΈΡ.
subnames = os.listdir(basedir)
#ΠΠ°Π»Π΅Π΅ ΡΠ΅ΡΠ΅Π· ΡΠΈΠΊΠ» ΡΠΏΠ»ΠΈΡΠΈΠΌ ΠΏΡΡΠΈ Π΄ΠΎ ΠΏΠΎΠ΄Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΠΉ.
for subname in subnames:
subpath = "%s/%s" % (os.path.dirname(basedir), subname)
#ΠΠΎΡΠΎΠΌ ΡΠ΅ΡΠ΅Π· walk, ΠΏΠΎΠ»ΡΡΠΈΠΌ ΠΊΠΎΡΡΠ΅ΠΆ (ΠΏΡΡΡ Π΄ΠΎ Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΠΈ, ΠΏΠΎΠ΄Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΡ, ΡΠ°ΠΉΠ»Ρ)
for path, subdirs, files in os.walk(subpath):
#ΠΡΠΎ Ρ Π½Π°Ρ "Π΅ΡΡ" ΠΌΠ΅ΡΡΠΎ? ΠΡΠΎΡ
ΠΎΠ΄ΠΈΠΌΡΡ ΠΏΠΎ ΡΡΠΈΠΌ ΡΠ°ΠΉΠ»Π°ΠΌ ΠΈ ΡΠΊΠ»Π°Π΄ΡΠ²Π°Π΅ΠΌ ΡΠ°Π·ΠΌΠ΅Ρ
for files in file:
#ΠΠΎΠ»ΡΡΠ°Π΅ΠΌ ΠΏΠΎΠ»Π½ΡΠΉ ΠΏΡΡΡ Π΄ΠΎ ΡΠ°ΠΉΠ»Π°.
filename = os.path.join(path, file)
#Π£Π·Π½Π°Π΅ΠΌ Π΅Π³ΠΎ ΡΠ°Π·ΠΌΠ΅Ρ ΠΈ ΡΠ²Π΅Π»ΠΈΡΠΈΠ²Π°Π΅ΠΌ ΡΠ°Π·ΠΌΠ΅Ρ ΠΏΠ°ΠΏΠΊΠΈ
sub_size += os.path.getsize(filename) /1024 /1024
print "%s - %.1f Mb" % (basedir[len[basedir]: ], sub_size)
Answer the question
In order to leave comments, you need to log in
If I understand correctly, then you need to move sub_size = 0:
import os
basedir = "/home/user/test/"
subnames = os.listdir(basedir)
for subname in subnames:
sub_size = 0
subpath = "%s/%s" % (os.path.dirname(basedir), subname)
for path, subdirs, files in os.walk(subpath):
for files in file:
filename = os.path.join(path, file)
sub_size += os.path.getsize(filename) /1024 /1024
print "%s - %.1f Mb" % (basedir[len[basedir]: ], sub_size)
Also studied this issue. There are many solutions, many cumbersome. As a result, I wrote a short function that calculates the size of the directory to a byte, the number of files in the directory (checked with the value from the folder property in Windows)
import os
from pathlib import Path
#ΠΡΡΠΈΡΠ»ΡΠ΅Ρ ΡΠ°Π·ΠΌΠ΅Ρ ΠΏΠ°ΠΏΠΊΠΈ, ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΠ°ΠΉΠ»ΠΎΠ² ΠΈ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΈΡΠ΅ΡΠ°ΡΠΈΠΉ ΡΡΠ½ΠΊΡΠΈΠΈ
def folderSize(path):
fsize = 0
numfile = 0
iteration = 0
for file in Path(path).rglob('*'):
if (os.path.isfile(file)):
fsize += os.path.getsize(file)
numfile +=1
iteration+=1
return fsize, numfile, iteration
print("ΠΡΡΠΈΡΠ»Π΅Π½ΠΈΠ΅ ΡΠ°Π·ΠΌΠ΅ΡΠ° Π²ΡΠ±ΡΠ°Π½Π½ΠΎΠΉ ΠΏΠ°ΠΏΠΊΠΈ...")
size, numfile, iteration = folderSize(folder)
print(f'ΠΡΠ±ΡΠ°Π½Π° ΠΏΠ°ΠΏΠΊΠ°: {folder}')
print(f'ΠΠ°ΠΉΠ΄Π΅Π½ΠΎ ΡΠ°ΠΉΠ»ΠΎΠ²: {numfile}')
print("Π Π°Π·ΠΌΠ΅Ρ ΠΏΠ°ΠΏΠΊΠΈ:")
print(f'{size} Bytes')
print(f'{size/1048576:.2f} Mb')
print(f'{size/1073741824:.2f} Gb')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question