【问题标题】:Why does os.stat().st_size return 0 for dir?为什么 os.stat().st_size 为 dir 返回 0?
【发布时间】:2025-12-30 10:55:11
【问题描述】:

所以,我正在阅读 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


【解决方案1】:

目录没有大小。如果你想计算一个目录使用了多少空间,循环遍历并聚合其中的文件大小

【讨论】:

  • 您能解释一下为什么 RealPython 中的示例(现在包含在问题中)显示的不是吗?
  • 我错过了一些答案。我相信这取决于操作系统。例如,Windows 目录没有大小。
最近更新 更多