实现说明
glob 按模式展开文件列表的核心是函数 show。
循环只出现在 for rel in ("a.log", "sub/b.log", "sub/deep/c.txt", "other/d.log"),它的每次迭代处理一个元素。
使用要点
- 每一步打印都带着自己的标签:
single:、recursive:、txt:。 - 值得导入的表面是
show;周围的辅助代码对片段是私有的。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 全部导入都来自标准库:glob、os、tempfile。 文件在加载时定义 show。
签名一览:def show(pattern, recursive=False)
核心语句
with open(path, "w", encoding="utf-8") as f:
f.write("x")
def show(pattern, recursive=False):
matches = glob.glob(os.path.join(root, pattern), recursive=recursive)
return sorted(os.path.relpath(m, root) for m in matches)
代码示例
import glob
import os
import tempfile
# Build a small tree so the patterns have something real to match
with tempfile.TemporaryDirectory() as root:
for rel in ("a.log", "sub/b.log", "sub/deep/c.txt", "other/d.log"):
path = os.path.join(root, rel)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write("x")
def show(pattern, recursive=False):
matches = glob.glob(os.path.join(root, pattern), recursive=recursive)
return sorted(os.path.relpath(m, root) for m in matches)
# Single star never crosses a directory separator
print("single:", show("*.log"))
# ** only descends when recursive=True is set
print("recursive:", show("**/*.log", recursive=True))
print("txt:", show("**/*.txt", recursive=True))