实现说明
os.scandir 复用目录扫描结果可以归结为函数 directory_report。
循环只出现在 for entry in entries,它的每次迭代处理一个元素。
使用要点
- 值得导入的表面是
directory_report;周围的辅助代码对片段是私有的。
常见问题
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 全部导入都来自标准库:os、tempfile。 文件在加载时定义 directory_report。
入口签名:def directory_report(root: str) -> list[str]
核心语句
with open(os.path.join(workdir, "a.txt"), "w") as handle:
handle.write("hello")
with open(os.path.join(workdir, "b.log"), "w") as handle:
handle.write("x" * 11)
代码示例
import os
import tempfile
def directory_report(root: str) -> list[str]:
lines = []
with os.scandir(root) as entries:
for entry in entries:
# DirEntry carries scan data from the directory listing,
# so is_dir() and stat() avoid a second syscall per file
if entry.is_dir():
lines.append(f"dir {entry.name}")
else:
lines.append(f"file {entry.name} {entry.stat().st_size} bytes")
return sorted(lines)
with tempfile.TemporaryDirectory() as workdir:
with open(os.path.join(workdir, "a.txt"), "w") as handle:
handle.write("hello")
with open(os.path.join(workdir, "b.log"), "w") as handle:
handle.write("x" * 11)
os.mkdir(os.path.join(workdir, "archive"))
for line in directory_report(workdir):
print(line)