[英]How to calculate size of immediate subfolders of a folder using os.walk()
How to calculate size of immediate subfolders of a folder using os.walk()
如何使用
os.walk()
计算文件夹的直接子文件夹的大小
Let say, I have a directory假设,我有一个目录
Directory-SubDirectory1
-SubDirectory2
-SubDirectory3
-SubDirectory4
So, I want to calculate size of all subdirectories individually, like:所以,我想单独计算所有子目录的大小,比如:
SubDirectory1 Size 100 MB
SubDirectory2 Size 110 MB
etc
I tried-我试过了-
for r, d, f in os.walk('/dbfs/mnt/Directory/.../'):
size = sum(getsize(join(r,n)) for n in f) / 1048576
print(size)
for s in d:
print (s)
Which returns the sizes of all subfolders and files in a long loop.它在一个长循环中返回所有子文件夹和文件的大小。
I want just immediate folder size result.我只想要立即的文件夹大小结果。
Using pathlib you can avoid a lot of OS specific headaches.使用 pathlib 可以避免很多特定于操作系统的问题。 It's also a bit more compact, use timeit to compare if you'd like, but I have a feeling it's quite a bit faster too.
它也更紧凑一些,如果您愿意,可以使用 timeit 进行比较,但我感觉它也快了一些。
from pathlib import Path
def dirsize(root):
size = 0
for f in Path(root).iterdir():
size += f.stat().st_size / 1048576
if f.is_dir():
print(f, "size: ", f.stat().st_size / 1048576)
return size
Try running with dirsize("/dbfs/mnt/Directory/...")
尝试使用
dirsize("/dbfs/mnt/Directory/...")
Here is an example, you can clean up the printing:这是一个示例,您可以清理打印:
>>> dirsize("E:\\Documents")
E:\Documents\knowledge size: 0.01171875
E:\Documents\Piano Scores size: 0.0078125
E:\Documents\poetry size: 0.00390625
E:\Documents\programming size: 0.00390625
E:\Documents\projects size: 0.0
E:\Documents\theory size: 0.00390625
16800.917387008667```
I made this finally and works fine-我终于做到了,效果很好-
import os
from pathlib import Path
root='/dbfs/mnt/datalake/.../'
size = 0
for path, subdirs, files in os.walk(root):
for f in Path(root).iterdir():
if name in files:
if f.is_dir():
size += os.path.getsize(os.path.join(path, name))
dirSize = size/(1048576)
print(f, "--Size:", dirSize)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.