【发布时间】: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
【问题讨论】:
-
你认为它应该返回什么?为什么?
-
os.stat()是依赖于实现的低级系统调用的包装器。stat标准库模块includes some tools to help interpret those results。 -
@KarlKnechtel 我认为它会返回 dir size 作为 realpython 示例输出,我将输出包含在我的问题中。
标签: python