首页 > 解决方案 > 为什么 os.stat().st_size 为 dir 返回 0?

问题描述

所以,我正在阅读 RealPython ' Context Managers and Python's with Statement '。所以当我在我的 python 终端中尝试 os.scandir() 方法时:

with os.scandir('.') as entry:
  for it in entry:
    print(it.name, ' --> ', it.stat().st_size)


Output of the above code in the terminal:

demo.py --> 5749
fonts -> 0
images -> 0
music --> 0
notes.txt --> 13
templates --> 0

文件的大小正确打印,但为什么所有目录由于某种原因被列为零?

来自 RealPython 的代码:

>>> import os

>>> with os.scandir(".") as entries:
...     for entry in entries:
...         print(entry.name, "->", entry.stat().st_size, "bytes")
...
Documents -> 4096 bytes
Videos -> 12288 bytes
Desktop -> 4096 bytes
DevSpace -> 4096 bytes
.profile -> 807 bytes
Templates -> 4096 bytes
Pictures -> 12288 bytes
Public -> 4096 bytes
Downloads -> 4096 bytes

标签: python

解决方案


目录没有大小。如果要计算目录使用了多少空间,请遍历并聚合其中的文件大小


推荐阅读