4 # https://stackoverflow.com/a/62000501/159695
6 if os
.path
.islink(path
):
7 return (os
.lstat(path
).st_size
, 0)
8 if os
.path
.isfile(path
):
10 return (st
.st_size
, st
.st_blocks
* 512)
11 apparent_total_bytes
= 0
14 for dirpath
, dirnames
, filenames
in os
.walk(path
):
15 apparent_total_bytes
+= os
.lstat(dirpath
).st_size
16 total_bytes
+= os
.lstat(dirpath
).st_blocks
* 512
18 fp
= os
.path
.join(dirpath
, f
)
19 if os
.path
.islink(fp
):
20 apparent_total_bytes
+= os
.lstat(fp
).st_size
24 continue # skip hardlinks which were already counted
25 have
.append(st
.st_ino
)
26 apparent_total_bytes
+= st
.st_size
27 total_bytes
+= st
.st_blocks
* 512
29 dp
= os
.path
.join(dirpath
, d
)
30 if os
.path
.islink(dp
):
31 apparent_total_bytes
+= os
.lstat(dp
).st_size
32 return (apparent_total_bytes
, total_bytes
)
34 def humanized_size(num
, suffix
='B', si
=False, decps
=1):
35 # decps for decimal places
37 units
= ['','K','M','G','T','P','E','Z']
41 units
= ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']
46 #return "%3.1f%s%s" % (num, unit, suffix)
47 return f
"%3.{decps}f {unit}{suffix}" % (num
)
49 #return "%.1f%s%s" % (num, last_unit, suffix)
50 return f
"%.{decps}f {last_unit}{suffix}" % (num
)
52 #s1,s2 = du("/Users/galaxy/t/t/t/t/Received")
58 print(humanized_size(s1
,decps
=2))
59 print(humanized_size(s2
,si
=True,decps
=4))